Sunday, July 26, 2009

How to retrieve checkbox value from mysql database

In this post I will show you how to retrieve checkbox value from database. As in the database in one field there resides multiple checkbox value so we need to be cautious while displaying checkbox data specially which box to be checked and which not.

Let's assume that field values for method #1 that is described inside http://arjudba.blogspot.com/2009/07/entering-mutiple-values-with-checkbox.html

We assume that checkbox field data are inserted into the database using comma separated values.

BY manually we are doing here for testing purpose.

mysql> delete from checkbox;
Query OK, 2 rows affected (0.00 sec)

mysql> insert into checkbox values('meat,vegetable,fastfood');
Query OK, 1 row affected (0.00 sec)

mysql> select * from checkbox;
+-------------------------+
| foods |
+-------------------------+
| meat,vegetable,fastfood |
+-------------------------+
1 row in set (0.00 sec)

Now following is the php code that is used to display for checkbox. Specially look at the condition,

if (in_array($food,$foods_ex)){
echo "<td>";
echo "<input type=\"checkbox\" name=\"food_cat[]\" value=$food checked>$food</input>";
echo "</td>";
}
else{
echo "<td>";
echo "<input type=\"checkbox\" name=\"food_cat[]\" value=$food>$food</input>";
echo "</td>";
}


<?
include('include/db.php');

$query="select foods from checkbox limit 1";

$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$row = mysql_fetch_array($result);
extract($row);
}
mysql_close();

?>

<html>
<body>
<form method="post">
<table width="50%">
<th>What is your favorite food?</th>
<tr>
<?
$array_food=array('fish','meat','vegetable','fastfood','soup');
$foods_ex=explode(',',$foods);
//print_r ($foods_ex);
foreach($array_food as $food){
if (in_array($food,$foods_ex)){
echo "<td>";
echo "<input type=\"checkbox\" name=\"food_cat[]\" value=$food checked>$food</input>";
echo "</td>";
}
else{
echo "<td>";
echo "<input type=\"checkbox\" name=\"food_cat[]\" value=$food>$food</input>";
echo "</td>";
}
}

?>

</tr>
<tr>

<td colspan="6" style="padding-left:30em">
<input type="submit" name="submit" value="save">
</td>
</table>
</form>
</body>
</html>

Whenever you execute above php code output like below will be displayed in the browser.










What is your favorite food?
fishmeatvegetablefastfoodsoup





Related Documents
http://arjudba.blogspot.com/2009/07/entering-mutiple-values-with-checkbox.html

No comments:

Post a Comment