$i=0;
while (db_data) {
$i++;
echo '<input type="checkbox" name="v['.$i.']" value="'.$url.'"';
if ($v[$i]) {
echo ' checked';
$s .= $url;
}
echo '/>';
}
I have the above array of checkboxes. It worked on my pc, but not on the server; it seems like the confusing part is on $v[$i]
.
$v is not defined, but sure used no where else. the problem is my checkbox selection never restored, and code never get into the if statement.
however, if i add the following, i can see the value. just the checkbox lost after the processing $v=$_POST['v']; while (list ($key,$val) = @each ($v)) { $x .= ' 11*'.$key.'-'.$val.'*22 '; }
my goal is to preserve the checkbox checked on the form, and i need the $s else开发者_开发技巧where. any solution to replace $v[$i]?
Can anybody help me fix this? Thank you.
The issue seems to be $v = $_POST. If you are just doing that then your conditional statement would need to be
if ($v['v'][$i]) {
///Checkbox
}
or just do $v = $_POST['v'].
Sorry, ignore above as you did mention you did that part. See below.
Here is working code.
<form action="" method="post">
<?php
$v = $_POST['v'];
$i=0;
while ($i < 4) {
$i++;
$url = "test.com/".$i;
echo '<input type="checkbox" name="v['.$i.']" value="'.$url.'"';
if ($v[$i]) {
echo ' checked="checked"';
$s .= $url;
}
echo '/> '.$url.'<br />';
}
?>
<input type="submit" name="submit" value="submit" />
</form>
I left the code pretty much the same to show you where you went wrong, but you should be checking the $_POST variable for exploits before using. If I were doing this as well, I would use a for count, but it's setup as a placeholder for your database code. Make sure that $url gets populated as well.
You could also do away with the $i variable like:
<?php
$v = $_POST['v'];
while (db_data) {
echo '<input type="checkbox" name="v[]" value="'.$url.'"';
if (is_array($v)) {
if (in_array($url,$v)) {
echo ' checked="checked"';
$s .= $url;
}
}
echo '/> '.$url.'<br />';
}
?>
Try to print_r($_POST) and then print_r($v) and see if anything comes up. If the $_POST works, then you know that it is being posted back to the page correctly. Then if the $v is working, then you know you set $v = $_POST correctly. Due to the fact that you don't actually give us any information on the db_data, I assume this is working correctly and displaying all the checkboxes on first load, so as long as it is posted and you are setting the $v variable, it should be working.
A side note is that you should validate the $_POST variables before using, but do that after you get things working.
change
name="v['.$i.']"
to
name="v[]"
the fact that PHP picks that up as an array is a unintended feature of PHP that wasn't intentionally designed. you don't need to set the indexes, just define it as an array.
精彩评论