Re: using for loop in function
| From: | Jim Lucas | Date: | Wed, 28 Mar 2007 05:52:52 +0000 |
| Subject: | Re: using for loop in function | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-251512@lists.php.net to get a copy of this message | ||
Richard Kurth wrote:
The function below will create a group of checkboxes it will also check the checkbox that is stored in the table field that is in $select_value this works fine if there is only one value in the variable but if there is more stored like 1,2,3,4 it will not work. I am trying to figure out how to use the following for loop to add the number to each checkbox and if they match mark the checkbox checked $ExplodeIt = explode(",",$select_value,",");function checkbox($sqlu,$name,$value1,$value2,$select_value){$Count = count($ExplodeIt); for ($i=0; $i < $Count; $i++) { } function checkbox($sqlu,$name,$value1,$value2,$select_value){ $name_result = safe_query($sqlu); while($rowu=mysql_fetch_array($name_result)){echo "<tr><td colspan=\"2\" align=\"left\"><input type='checkbox' name='" . $name . "[" . $rowu[$value1] . "]' value=\"$rowu[$value1]\"";if($select_value==$rowu[$value1]) { echo " checked>$rowu[$value2]\n</td></tr><BR>"; }else{ echo ">$rowu[$value2]\n</td></tr><BR>"; }} } I have used in_array as a way of doing what you are looking for.
$name_result = safe_query($sqlu);
while ( $rowu = mysql_fetch_array($name_result) ) {
$checked = '';
if ( in_array($rowu[$value1], $select_value) ) {
$checked = ' checked="checked"';
}
echo <<<HTML
<tr>
<td colspan="2" align="left">
<input
type="checkbox"
name="{$name}[{$rowu[$value1]}]"
value="{$rowu[$value1]}"
{$checked} />{$rowu[$value2]}
</td>
</tr>
HTML;
}} Personally, I would change your SQL query to return only the two columns that you are wanting to display. And also use the mysql_fetch_assoc() SELECT id AS colA, name AS colB FROM myTable; and not this SELECT * FROM myTable; This would then allow me to write your function this way. function checkbox($sqlu,$name,$selected=array()){
if ( ( $name_result = safe_query($sqlu) ) === false ) {
die('something went wrong');
}
while ( $rowu = mysql_fetch_assoc($name_result) ) {
$checked = '';
if ( in_array($rowu['colA'], $selected) ) {
$checked = ' checked="checked"';
}
echo <<<HTML
<tr>
<td colspan="2" align="left">
<input type="checkbox"
name="{$name}[{$rowu['colA']}]"
value="{$rowu['colA']}"
{$checked} />{$rowu['colB']}
</td>
</tr>
HTML;
}} Hope this helps