dimanche 31 mai 2015

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

I have found a question recently (http://ift.tt/1HDLKzE). Now, I would like to create a template for the HTML generation, as it seems a good idea to avoid code duplication. This is how my html is generated:

// ---------------------------------------
// --- 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);

All PHP Code for checkbox groups : http://ift.tt/1d7t7ft

How can I implement a function which would generate a checkbox group, so I would simply call it as a function.

Hope somebody may help me out. Thank you.




Aucun commentaire:

Enregistrer un commentaire