Forum Moderators: coopster
I've been trying to solve a problem this afternoon and every search I do for it brings me back here. However, the posts I've found seem to be about more complex problems than mine, so I'm still a bit confused. (Yep, a beginner...)
I'm using PHP to create a list of options with checkboxes from a MySQL database. Making the checkboxes appear with their names is no problem, but I can't figure out how to use the checkboxes to add data to an array. That is to say, the page initially displays just fine, but if I click submit, nothing happens.
I've put a bunch of places where I print out what's going on with the page, and the only real problem seems to be that $myarray stays empty. I've seen so many different ways to do this that I can't figure out which way would apply to my very simple case.
$query = "SELECT charID, charname FROM people ORDER BY charID ASC";
$result = @mysql_query ($query);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<input type="checkbox" name="' . $myarray[] . '" value="' . $row['charID'] . '" />' . $row['charname'] . '<br />';
} I'd be grateful for any advice!
ETA: The error I get from the line starting with echo is:
Fatal error: Cannot use [] for reading in C:\Program Files\xampp\htdocs\xampp\practice\page2.php on line 19
Or you can use a shorthand:
$myarray[] = 0;
$myarray[] = 1;
$myarray[] = 2;
Those two are equivalent. Specifically what the error is telling you is that you can't use the second mehod to get the values back out - you have to be explicit:
echo $myarray[0];
echo $myarray[1];
Since you're making the checkbox values the charID, you can make them an array like this:
echo '<input type="checkbox" name="myarray[]" value="' . $row['charID'] . '" />'
Then you'll refer to them collectively as (assuming method="post"):
$_POST['myarray']
and to get the values out individually, you can do this:
foreach($_POST['myarray'] as $checkbox) {
// $checkbox will have the value assigned to it from $row['charID']
}
Note that checkboxes which have been checked will be in the array, each with its assigned value. Checkboxes which were not checked on the form will not exist in the array.
Thanks for putting it so clearly--works like a charm!