如何为复选框组创建模板以避免服务器端代码重复?

How to create a template for checkbox groups to avoid code duplication at server side?

最近发现一个问题(whosebug.com/questions/30556100/how-to-uncheck-all-checkboxes-if-one-checkbox-checked)。现在,我想为 HTML 代创建一个模板,因为这似乎是避免代码重复的好主意。这就是我的 html 的生成方式:

// ---------------------------------------
// --- Populate "Body Type" dropdown list:
// ---------------------------------------

// for populate body types:
$bodytype = array(); 

// Select exsiting body type from database:  
$prep_stmt = " SELECT id,   name FROM body_type";

$stmt = $mysqli->prepare($prep_stmt);

if ($stmt) {
    // Bind "$userId" to parameter.
    //$stmt->bind_param('i', $userId);  
    // Execute the prepared query.
    $stmt->execute();    
    $stmt->store_result();

    // get variables from result.
    $stmt->bind_result($id, $name);

    // Fetch all the records:
    while ($stmt->fetch()) {

        // XSS protection as we might print these values
        $name = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $name);
        $id   = filter_var($id,FILTER_SANITIZE_NUMBER_INT);

        $type  = "<label class='checkbox-inline'>\n";
        if ($name == 'Any'){
            $type .=    "<input type='checkbox' id='bodyTypeAny' name='bodyTypeCheck[]' value='{$id}'> {$name}\n";
        } else {
            $type .=    "<input type='checkbox' id='' name='bodyTypeCheck[]' value='{$id}'> {$name}\n";
        }
        $type .= "</label>\n";  
        //Add body types to array
        $bodytype[] = $type;    
    }   
} else {
    echo 'Database error';
}   

// Close the statement:
$stmt->close();
unset($stmt);

所有 PHP 复选框组代码:http://pastebin.com/NXN6ZzcK

我如何实现一个可以生成复选框组的函数,所以我会简单地将其称为函数。

希望有人能帮助我。 谢谢你。

在执行以下步骤之前,请将您的工作版本保存在某处,以确保您可以在需要时回滚。

您可以为模板创建一个 class,如下所示:

class TemplateEngine {

    public static function getCheckboxTemplate($input, $templateName) {
        $template = "";
        foreach ($input as $element) {
            $template .= "<label class='checkbox-inline'>\n";
            $template .= "<input type='checkbox' ".(($element["name"] === "Any") ? ("id='".$templateName."Any'") : (""))." name='".$templateName."Check' value='".$element["id"]."'>".$element["name"]."\n";
            $template .= "</label>\n";
        }
        return $template;
    }

}

确保在一个单独的文件中创建 class,您也将在该文件中实现以后的模板,并且 require/include 该文件。然后你可以像这样使用它:

// ---------------------------------------
// --- Populate "Body Type" dropdown list:
// ---------------------------------------

$template = "";
// Select exsiting body type from database:  
$prep_stmt = " SELECT id,   name FROM body_type";

$stmt = $mysqli->prepare($prep_stmt);

if ($stmt) {
    // Bind "$userId" to parameter.
    //$stmt->bind_param('i', $userId);  
    // Execute the prepared query.
    $stmt->execute();    
    $stmt->store_result();

    // get variables from result.
    $stmt->bind_result($id, $name);
    $input = array();

    // Fetch all the records:
    while ($stmt->fetch()) {

        $input[]= array("name" => preg_replace("/[^a-zA-Z0-9_\-]+/", "", $name), "id" => filter_var($id,FILTER_SANITIZE_NUMBER_INT));
    }
    $template = TemplateEngine::getCheckboxTemplate($input, "bodyType");   
} else {
    echo 'Database error';
}   

// Close the statement:
$stmt->close();
unset($stmt);

而不是使用 $bodytype array,您可以简单地:

echo $template;

代码未经测试。如果有错别字,请告诉我:)

编辑:进一步模板化:

class TemplateEngine {

    public static function getCheckboxTemplate($input, $templateName) {
        $template = "";
        foreach ($input as $element) {
            $template .= "<label class='checkbox-inline'>\n";
            $template .= "<input type='checkbox' ".(($element["name"] === "Any") ? ("id='".$templateName."Any'") : (""))." name='".$templateName."Check' value='".$element["id"]."'>".$element["name"]."\n";
            $template .= "</label>\n";
        }
        return $template;
    }

    public static function getCheckboxDatabaseWrapperTemplate($tableName, $templateName, $mysqli) {
        $template = "";
        // Select exsiting body type from database:  
        $prep_stmt = " SELECT id,   name FROM ".$tableName;

        $stmt = $mysqli->prepare($prep_stmt);

        if ($stmt) {
            // Bind "$userId" to parameter.
            //$stmt->bind_param('i', $userId);  
            // Execute the prepared query.
           $stmt->execute();    
           $stmt->store_result();

           // get variables from result.
           $stmt->bind_result($id, $name);
           $input = array();

           // Fetch all the records:
           while ($stmt->fetch()) {

               $input[]= array("name" => preg_replace("/[^a-zA-Z0-9_\-]+/", "", $name), "id" => filter_var($id,FILTER_SANITIZE_NUMBER_INT));
           }
           $template = TemplateEngine::getCheckboxTemplate($input, $templateName);   
       } else {
           echo 'Database error';
       }   

       // Close the statement:
       $stmt->close();
       unset($stmt);
       return $template;
    }

}