...

View Full Version : Update database with dynamic checkbox info



guvenck
02-17-2006, 08:12 AM
Hi,

I have a table with following structure. This table is to keep records of which titles the member has on his list.

tablea:
ID title checked


I pull records from the table and display them. He can check or uncheck the results and submit the form for update.




<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">

<?php

$result = mysql_query("SELECT ID,title,checked FROM tablea") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
extract($row);
echo "$title";
echo "&nbsp;";
echo "<input type=\"checkbox\" name=\"checkbox[]\"";
if ($checked==1) {
echo " checked";
}
echo ">";
echo "<br />";
}
?>

<input type="submit" value="Update Database">
</form>



When the form is submitted, I need a foreach loop that checks what is checked or unchecked, then updates the database tablea.checked, which is type ENUM '0','1'.

I am stuck because if a checkbox is not checked, it is not submitted at all. So somehow I need to check existing database value as well...

degsy
02-17-2006, 01:57 PM
You could do a global update statement to reset all fields to 0 then use your submitted data to update the checked values to 1

guvenck
02-18-2006, 10:20 AM
Degsy,
Nice tip, will do it. Can you also give an example for the foreach loop?

degsy
02-21-2006, 02:43 PM
You don't need to use a foreach loop.

You will be recieving an array so you can use IN.



echo "<input type=\"checkbox\" name=\"checkbox[]\" value=\"$id\"";
if ($checked==1) {
echo " checked";
}
echo ">";
echo "<br />";



"UPDATE tablea SET checked = 1 WHERE id IN (" . $_POST['checkbox'] . ")";

http://www.w3schools.com/sql/sql_in.asp

guvenck
02-21-2006, 05:06 PM
I used this loop, is working:



if(isset($_POST['submit'])) {
include ("db.php");
$reset = "DELETE FROM table WHERE usrid='$myid'";
$doreset = mysql_query($reset) or die(mysql_error());
foreach ($_POST['check_id'] as $value){
$update = "INSERT table (usrid,rdid) VALUES ($myid,$value)";
$doupdate = mysql_query($update) or die(mysql_error());
}
}

degsy
02-22-2006, 02:25 PM
ok, just if you did have thousands of records it would be quicker to perform one query instead of thousands of queries.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum