How to insert value from checkbox in MySQL?

MySQL

`field1` tinyint(1) NOT NULL default '1',
`field2` tinyint(1) NOT NULL default '1',
`field3` tinyint(1) NOT NULL default '1',
`field4` tinyint(1) NOT NULL default '1',
`field5` tinyint(1) NOT NULL default '1',

HTML

<form method="post">
<input type="hidden" name="blah" value="blah">

<input type="checkbox" name="field1" value="1">
<input type="checkbox" name="field2" value="1">
<input type="checkbox" name="field3" value="1">
<input type="checkbox" name="field4" value="1">
<input type="checkbox" name="field5" value="1">

<button type="submit">Submit</button>

</form>

Php

mysql_query("UPDATE `table` SET `field1` = '$_POST[field1]', .......");

So, I want to do the following:

a) If checked, I want to update the corresponding field with 1

b) If unchecked, I want to update the field with 0

And now, please tell me that I do not need to do this, and that there is a better way to do this:

$field1 = isset($_POST['field1']) ? 1 : 0;
$field2 = isset($_POST['field2']) ? 1 : 0;
$field3 = isset($_POST['field3']) ? 1 : 0;
$field4 = isset($_POST['field4']) ? 1 : 0;
$field5 = isset($_POST['field5']) ? 1 : 0;

mysql_query("UPDATE `table` SET `field1` = '$field1', `field2` = '$field2' ....");
+3
source share
6 answers

you can use field[]

<input type="checkbox" name="field[0]" value="1">
<input type="checkbox" name="field[1]" value="1">

So you can do a simple loop:

for($i=0;$i<5;$i++)
   $field[$i] = isset($_POST['field'][$i]) ? 1 : 0;

And then create your SQL

If you want to skip the isset section, you can use the type of radio signal, so you always have the value 1or 0.

+3
source

You have a hole for SQL injection:

enter image description here horror coding

mysql_query("UPDATE `table` SET `field1` = '$_POST[field1]', .......");

Change it to:

$field1 = mysql_real_escape_string('$_POST[field1]');
....
mysql_query("UPDATE `table` SET `field1` = '$field1', .......");
/*                                         ^       ^ these quotes are vital */

$vars .

+2

,

<input type="hidden" name="field1" value="0">
<input type="checkbox" name="field1" value="1">
<input type="hidden" name="field2" value="0">
<input type="checkbox" name="field2" value="1">

, , ( ), 0 .

, // PHP, SQL- ( , , Firebug value="2", )

+1

, .

1 0 , , .

, PHP $_POST var

0

If the checkbox is not selected, it is not submitted with the form, so you do not have it in the $ _POST array.

You can use hidden input and a little javascript, but this is less code if you are running part of PHP.

0
source

I think you want to not write as many lines of code to check the values ​​of the flags.
Maybe you can try this (I have not tried it yet):

$field = 'field';

for(int i=1; i<=5, ++i){
    $($field.1) = isset($_POST['field'.i]) ? 1 : 0;

}
0
source

All Articles