Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Please help -- Checkboxes -- So Close, Yet So Far

Status
Not open for further replies.

jjfletch

Technical User
Sep 4, 2004
13
US
Newbie here....

I have a form that has a number of checkboxes. Upon initial submission, the values of the checked boxes are stored as one variable via "implode" and placed into my database.

In an effort to make the form editable (that is, a user can select/deselect boxes as they wish) , I've been trying to place "checked" inside the input tag for the values that are actually in the database.

But, I can't figure out how to check to see if that particular item is in the database... I've pasted the code below and indicated where I'm having a problem.

$array = array('Milk', 'Eggs', 'Bread', 'Lettuce' , 'Cookies');

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

while($row=mysql_fetch_array($result)) {
$item=$row['items'];
$brd=$row['brand'];
$st=$row['store'];
}

foreach ($array as $item) {

if ( $item is in database) // THIS IS WHERE I'M STUCK
$chk = 'checked';
else
$chk = '';
echo "<input type='checkbox' name='$item' value='1' $chk> $item<br>";
}
 
you might use a different SELECT:

$s=implode(',',array);
$sql="SELECT * FROM qtable WHERE items IN ('$s')";
 
jjfletch,

You may prefer a query as sysadmin42 has suggested, but there is a function
called in_array() that checks the array for a value.

Example:
Code:
 while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
 	 $tmp = explode(",", $row['items']);
	 foreach($tmp as $value){
	 if(in_array($value, $array)) print $value;
	 }
 }

This example assumes you have used the comma in your item implode.

Thanks,


Hope it's helpful.

Good Place to "Learn More">>
 
Hi there.
Your code is correct, and you just need to change something.

$array = array('Milk', 'Eggs', 'Bread', 'Lettuce' , 'Cookies');

$query = "SELECT * FROM qtable WHERE id='$did'";
$result = @mysql_query ($query);
//need to store in array
while($row=mysql_fetch_array($result)) {
$item[]=$row['items'];
$brd[]=$row['brand'];
$st[]=$row['store'];
}
//u first use $item, which is a duplicate of the above.
foreach ($array as $theitem) {
if (in_array ($theitem, $item)) // check existence of item in the $itemarray
$chk = 'checked';
else
$chk = '';
echo "<input type='checkbox' name='$item' value='1' $chk> $item<br>";
}

Or in short, you could write:

$chk = (in_array ($theitem, $item)) ? " checked" : "";
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top