Page 1 of 1

Checkbox Prepopulation -- help?

Posted: Sun Dec 11, 2005 10:56 am
by jjfletch
I have a form that's editable, but need some help displaying prechecked checkboxes.

I've simplified things for the example I'm about to use, but essentially, the tables I've set up are:

Colors_Table
------------
ID | Color_Name
1 | red
2 | blue
3 |green
4 | yellow

And

Color_Management
--------------------
ID | Color | Name
1 | red,blue | Joe
2| yellow, green | Sam

First, I want to build the array based on the values in the Colors_Table, so I use:

Code: Select all

$query = "SELECT * FROM Colors_Table";
        $result = @mysql_query($query);
        $lookup_color = array(); 
        while ($row = mysql_fetch_array ($result)) {
                $ID = $row['ID']; 
                $lookup_color[$ID] = $row['Color_Name'];
                }
Which works fine.

Then, I want to create checkboxes for Joe and precheck them according to his prior input. This is basically where I'm stuck.

I tried this:

Code: Select all

$id = $_GET['id'];

$query = "SELECT * FROM Color_Management WHERE ID='$id'";
        $result = @mysql_query($query);
         
        while ($row=mysql_fetch_array($result)) {
                $color_exp = explode(',',$row['Color']);
                $colors = $row['Color'];
                }
                 
        foreach ($lookup_color as $colors) {
                if (in_array($colors,$color_exp)) {
                        $chk = 'checked';
                } else {
                        $chk = '';
                }
                echo "<input type='checkbox' name='colors[]' value='$colors' $chk>$colors<br />";
        }
But, I keep getting this error message:

Warning: in_array(): Wrong datatype for second argument

Can someone help me out?

Posted: Sun Dec 11, 2005 1:35 pm
by John Cartwright
before the in_array() function, input this

Code: Select all

echo '<pre>';
print_r($color_exp);
echo '</pre>';
to see what $color_exp actually is, apparantly it's not an array yet, which brings us back to the explode() function.. are you sure your string is going to have a , (comma) in it?


After re-reading your post your doing a couple things wrong

Code: Select all

//added use of intval to guarantee $id is an int
$id = intval($_GET['id']);

$query = "SELECT * FROM Color_Management WHERE ID='$id'";
$result = @mysql_query($query);

//if your not wanting to use mysql_error() to capture query failures,
//then do something like this         
if (!$result) {
   echo 'Something wen\'t wrong';
}
else {
   //no need for a loop here
   $row=mysql_fetch_array($result)) {
   $color_exp = explode(',',$row['Color']);
   $colors = $row['Color'];
                 
   foreach ($lookup_color as $colors) {
      if (in_array($colors,$color_exp)) {
         $chk = 'checked';
      } 
      else {
         $chk = '';
      }
      echo "<input type='checkbox' name='colors[]' value='$colors' $chk>$colors<br />";
   }
}