Dynamically creating checkboxes
i am new to php.I want to dynamically create che开发者_StackOverflow社区ck boxes upon the result fetched from MySQL.If i have 10 records in employee Table so it must create 10 check boxes with employee name as value.I had seen several tutorials to make array of check boxes etc but could not fix the problem.Please anyone there to help!!!
Try this out:
<?php
//Create the query
$sql = "SELECT `name` FROM Employees";
//Run the query
$query_resource = mysql_query($sql);
//Iterate over the results that you've gotten from the database (hopefully MySQL)
while( $employee = mysql_fetch_assoc($query_resource) ):
?>
<span><?php echo $employee['name']; ?></span>
<input type="checkbox" name="employees[]" value="<?php echo $employee['name']; ?> /><br />
<?php endwhile; ?>
The example you see above relies on two things to actually function properly:
- You're using MySQL
- Your SQL-query must retrieve the employees' names (so that you can use them in the loop
MySQL is just a source of data. The same process would apply to making a checkbox list from ANY data source (array, file contents, database, etc...). A skeleton framework for the process would be:
$sql = "select idfield, namefield FROM sometable ...";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo <<<EOL
<input type="checkbox" name="name[]" value="{$row['namefield']}" /> {$row['namefield']}<br />
EOL;
}
Note that I've use the "name field"as you specified. But consider the case where you've got 2 or more John Smith's working for you - it is far more reliable to use the employee's ID number (whatever it may be in your database) than their name.
Lets say the result you fetched is in the $result array.
The array has 10 sub-arrays - each one looking like this:
[0] => array
['name'] => 'ZainShah'
[1] => array
['name'] => 'Stack'
The easiest way to do this is:
foreach ( $result as $key => $employee ) {
echo '<label for="employee' . $key . '">' . $employee['name'] . '</label>'
echo '<input type="checkbox" name="employee[]" id="employee' . $key . '" value="' . $employee['name'] . '" />';
}
I have made it easy to create checkboxes as well as radio buttons in any php form. Only thing is I am using Codeigniter MVC framework.
Here is the function definition that you can insert in your common-model or any helper file.
function createOptions($fieldName, $labelsArray=array(), $selectedOption, $fieldType,$valuesArray = array()) {
$returnString = '';
if(count($valuesArray)!=count($labelsArray))
$valuesArray=$lebelsArray;
if ($fieldType === 'checkbox') {
for ($i=0;$i<count($labelsArray);$i++) {
$returnString.='   <input type="checkbox" name=' . $fieldName.' value='.$valuesArray[$i].' id='.$valuesArray[$i];
if(in_array($valuesArray[$i], $selectedOption)){
$returnString.=' checked="checked" ';
}
$returnString.=' />  <label>'.$labelsArray[$i].'</label>';
}
}
if ($fieldType === 'radio') {
for ($i=0;$i<count($labelsArray);$i++) {
$returnString.='  <input type="radio" name=' . $fieldName.' value='.$valuesArray[$i].' id='.$valuesArray[$i];
if($valuesArray[$i]== $selectedOption)
$returnString.=' checked="checked" ';
$returnString.=' /><label>'.$labelsArray[$i].'</label>';
}
}
return $returnString;
}
And, you have to call this function in view file as,
<?php
echo $this->common_model->createOptions('userHobbies[]', $hobbyOptions, $userHobbies, 'checkbox'); ?>
First parameter is name of checkbox field or radio field, which is always gonna be same for all options for both cases. Second is labels array, Third is selected options which will show those options as checked while loading the form. Fourth is type of field that will be a string as 'checkbox' or 'radio'. Fifth will be values array, which, if present, will contain values for labels in the same order as that of labels. If its absent, labels array will be teated as values array
This is fairly straightforward. I'll assume that your MySQL result data is in an array called $employees, containing at least 2 elements: id and name. You mention that the "value" of the checkbox needs to be the name, but I'll assume that's what you want displayed in the HTML next to the checkbox. It would be better to have the "value" be the id of the database record for each employee (since employees might have the same name). Creating the HTML for the checkboxes is simply a matter of iterating through them with a foreach() loop, and creating a php variable to hold the HTML.
So, assuming your $employees array looks something like this:
[0] =>
'id' => '1'
'name' => 'Sam Jones'
[1] =>
'id' => '2'
'name' => 'Tom Smith'
[2] =>
'id' => '3'
'name' => 'Sarah Conners'
Just need to run through the array and create the output:
// init the var to hold the HTML
$output = '';
// cook the HTML
foreach ($employees AS $k=>$v) {
$output .= "<input type='checkbox' name='employee_array[]' value='" . $v['id'] . "'> " . $v['name'] . "<br />";
}
In your HTML form, just echo the $output variable. Notice that the ".=" operand is used to append to the $output variable I created. And the "name" of the form field ends in "[]". This will create an array named "employee_array" that gets passed back to PHP when the form is submitted. Each item that is checked becomes an element of that array, with its value being the ID of the employee record.
Hope that makes sense...
set echo in for loop
you will always be able to set the loop variable
now simply echo/print the code
精彩评论