Reputation: 83
I have this system where I store checkbox data into an array. So if it is checked it will put the value in the array. Let's say that there are 6 checkboxes, and I check the last 3, then array values [3][4] and [5] will have values, correct? Ok.
Now if the array values [0][1] and [2] are 0 as they haven’t been checked, what is their value?
The question is, that when I do a MySQL insert to a database and I use this code?
mysqli_query($con,"INSERT INTO accounts (chk1, chk2, chk3, chk4, chk5, chk6) VALUES ('$checkbox[0]', '$checkbox[1]', '$checkbox[2]', '$checkbox[3]', '$checkbox[4]', '$checkbox[5]'");
Now, when that query executes, if the first arrays are nothing, it will skip them and pretend they are not there. Is there a way I can make them just put 0 if they haven’t been checked.
Upvotes: 1
Views: 129
Reputation: 3280
Why not just apply a DEFAULT 0
constraint to every check{n}
field, in the database?
That way, (1) you will make your data protect themselves regardless of the interface and (2) there would be less code to be written, since less checks would be necessary.
Upvotes: 1
Reputation: 3862
put this code before your query
$checkbox[0]=(isset($checkbox[0]))?$checkbox[0]:0;
$checkbox[1]=(isset($checkbox[1]))?$checkbox[1]:0;
$checkbox[2]=(isset($checkbox[2]))?$checkbox[2]:0;
$checkbox[3]=(isset($checkbox[3]))?$checkbox[3]:0;
$checkbox[4]=(isset($checkbox[4]))?$checkbox[4]:0;
$checkbox[5]=(isset($checkbox[5]))?$checkbox[5]:0;
OR
// get $_POST value
function initPostValue($elementVar, $defVal=null) {
if(!isset($_POST[$elementVar])){
$_POST[$elementVar] = $defVal;
}
return $_POST[$elementVar];
}
// get $_REQUEST value
function initRequestValue($elementVar, $defVal=null) {
if(!isset($_REQUEST[$elementVar])){
$_REQUEST[$elementVar] = $defVal;
}
return $_REQUEST[$elementVar];
}
// get $_GET value
function initGetValue($elementVar, $defVal=null) {
if(!isset($_GET[$elementVar])){
$_GET[$elementVar] = $defVal;
}
return $_GET[$elementVar];
}
Example : $checkbox[0] = initRequestValue('checkbox[0]',0);
use above function for get any value take from $_GET,$_POST,$_REQUEST so there are no need to for check empty
Upvotes: 0
Reputation: 19547
$data = array();
for($a=0; $a<max(array_keys($checkbox)); $a++) {
$data["chk$a"] = $checkbox[$a] ?: '0';
}
$sql = 'INSERT INTO accounts (\''.implode('\',\'', array_keys($data)).'\') VALUES ('.implode(',',$data).')';
Upvotes: 0
Reputation: 11625
They will not have values.
You also want to sanity check them using mysqli_real_escape_string
.
I'd do an isset
on each checkbox item and set it to 0 if it's not there.
Code example as requested:
$checkbox[0] = isset($_REQUEST['checkboxName']) ? mysql_real_escape_string($_REQUEST[$_REQUEST['checkboxName']]) ? 0 ;
if the value is always 1
, then use 1
instead of mysql_real_escape_string($_REQUEST[$_REQUEST['checkboxName']])
Upvotes: 0