Forum Moderators: coopster

Message Too Old, No Replies

How to update mysql using checkbox in a form

         

greenjeyes

7:51 am on Aug 5, 2007 (gmt 0)

10+ Year Member



Hello, I'm a newbie and want to write a code so that when a checkbox in a form is checked/unchecked, some data is updated in the mysql database.
This is the what I came up with below. The form works but the database does not update, please what is wrong?:

$ret .= '<script type="text/javascript">';
function ratechoice()
{ if(document.form.checkBox.checked == true)
{
$value = 'yes';
}
else if(document.form.checkbox.checked == false)
{
$value = 'no';
}
}
$ret .= '</script>';

$ret .= '<form action="' . $_SERVER['PHP_SELF'] . '" method="get">';
$ret .= '<div>';
$ret .= 'Rate photo<input type= "checkbox" name="checkbox" onclick="submit();" onsubmit="ratechoice();">';
$ret .= '</div>' . "\n";
$ret .= '</form>';

if($value = 'yes')
{
$query = "UPDATE `media` SET `rate_choice` = 'yes'";
}
else if($value = 'no')
{
$query = "UPDATE `media` SET `rate_choice` = 'no'";
}

Habtom

7:54 am on Aug 5, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



if($value = 'yes')
{
$query = "UPDATE `media` SET `rate_choice` = 'yes'";
}
else if($value = 'no')
{
$query = "UPDATE `media` SET `rate_choice` = 'no'";
}

You have used a single "=" instead of "==", you are not comparing them, it is being set.

if($value == 'yes')
{
$query = "UPDATE `media` SET `rate_choice` = 'yes'";
}
else if($value == 'no')
{
$query = "UPDATE `media` SET `rate_choice` = 'no'";
}

As for the updating, are your running the query.
Does this line flow the if condition:
mysql_query($query);

Habtom

greenjeyes

6:01 pm on Aug 5, 2007 (gmt 0)

10+ Year Member



Hello Habtom, thanks for the quick reply. I corrected my mistakes and it works now but now I need to return the page with the checkbox checked if one checks it and if one unchecks it, I need to return the page unchecked. Any clue on how to do that? Thanks a lot.

coopster

1:23 am on Aug 8, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, greenjeyes.

Maintaining the state of checkboxes is always a joy in <form>s. If any given checkbox option is not selected, it is not passed in the array back to the script. So, you need to keep track of that information either in a session or hidden form fields, a cookie, etc. and update your tracking information server-side accordingly.

jonk

7:00 pm on Aug 9, 2007 (gmt 0)

10+ Year Member



Can I add a question to this?

Instead of radio buttons, I'd like to set a variable using a drop down. I have seen how to 'onchange' a dropdown, but don't know how to use one where it is submitted to a variable when I submit it with text in input and textarea fields. Basically, I have a directory where I can enter links, titles and descriptions to my sql db, but want to use the dropdown for 'category' and publish 'yes/no' - hope his makes sense!