tags:

views:

19

answers:

2

Currently, my checkboxes are built by a static array:

$choices = array(
   'key_1' => 'Name 1',
   'key_2' => 'Name 2',
    ...
   'key_n' => 'Name n');

<? foreach (@choices as $key => $choice) {
      echo "<input type="checkbox" name='keys[]' value='$key'/> $choice <br />";
   } ?>

and I access the return values by:

$_POST['keys']

What if I want the $choices array to be build from table data? How can I build a PHP array (which is good for building checkbox choices) from a table? Thanks

A: 

Well first of all you need the data.

$result = mysql_query("SELECT * FROM options");
if($result){

 while($r = mysql_fetch_array($result)){

echo "<input type=\"checkbox\" name=\"keys[]\" value=\"".$r["key"]."\">".$r["choice"]."</option>";

 }

}
Digital Human
A: 

Well, you could try this:

$choices = array()
$query = mysql_query("SELECT field1, field2 FROM ...");
if (mysql_num_rows($query))
{
    while ($row = mysql_fetch_array($query))
    {
        $choices[$row['field1']] = $row['field2'];
    }
}

Now $choices contain what you need.

mr.b