Forum Moderators: coopster

Message Too Old, No Replies

Another Checkbox query

This time on multiple checkboxes

         

woldie

3:15 pm on May 1, 2004 (gmt 0)

10+ Year Member



What I am trying to achieve again is when a user selects multiple checkboxes it places a 1 in the DB, if it deselects it then it place a 0 in the DB

What I am doing here is get the userid (pri key) and live field from DB, so if its one then checked. So you could have 10 users and select and deselect whatever but when you submit it stores into an array called live with userid assosciated with it

Code:

if (isset($live))
{
// again something needs to be done here
foreach ($live as $var => $value)
echo $value;
mysql_query("update tablename set
live=$value
where user_num=$var");
}

<form>
<td align="center">
<?
if ($DBlive==1)
{
?>
<input type=checkbox name=live[<? echo $DBuser_num?>] value=1 checked>
<?
}
else
{
?> <input type=checkbox name=live[<? echo $DBuser_num?>] value=1>
<?
}
?></td>

</form>

Netizen

3:27 pm on May 1, 2004 (gmt 0)

10+ Year Member



I think you need to retrieve all the users from the DB and check if the var is set

$users=<some query from DB>;

foreach ($users as $userID) {
if (isset($live[$userID])) {
$liveFlag=1;
} else {
$liveflag=0;
}

mysql_query("update tablename set live=$liveFlag
where user_num=$userID");

}

I hope that helps

woldie

3:48 pm on May 1, 2004 (gmt 0)

10+ Year Member



Thanks Netizen,

The $DBuser_num is the userid for each row of the table, which is passed when you select or perhaps deselect so it knows which rows in the DB to change.

if (isset($live))
{
// again something needs to be done here
foreach ($live as $var => $value)
echo $value;
mysql_query("update tablename set
live=$value
where user_num=$var");
}

<form>
$result=mysql_query("select user_num,live from tablename");

while (list($DBuser_num,$DBlive)=mysql_fetch_row($result))
{
<?
if ($DBlive==1)
{
?>
<input type=checkbox name=live[<? echo $DBuser_num?>] value=1 checked>
<?
}
else
{
?> <input type=checkbox name=live[<? echo $DBuser_num?>] value=1>
<?
}
}
?>

</form>

httpwebwitch

8:19 pm on May 4, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



tip: you can avoid the "IF" and make this code cleaner using the?: operator.

<form>
<?php
$result=mysql_query("select user_num,live from tablename");
while (list($DBuser_num,$DBlive)=mysql_fetch_row($result)){
print("<input type='checkbox' name='live[".$DBuser_num."]' value='1' ".($DBlive?' CHECKED':'').">");
}
?>
</form>

Netizen

9:20 pm on May 4, 2004 (gmt 0)

10+ Year Member



I find inline IFs like that harder to follow in most instances. But then I try to write code that is easily readable for my own benefit and the people I work with!