Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$_POST as $key => $value using checkboxes

Tags:

http

checkbox

php

I am having trouble getting a form to update the information passed from a check box. I was given this code.

$one = isset($_POST['one']) ? 'on' : 'off'; 

This works great as long as I call each check box separately. My problem is I have approximately 200 checkboxes in total.

Here is the code I am using to UPDATE with. Can anyone help me to figure out where to insert the code I was given into my present code? I've tried all sorts of variations.

if($_POST['submit']){
    if(!empty($applicant_id)){
        $sql = "UPDATE play SET ";
        foreach($_POST as $key => $value){
                if(($key != 'submit') && ($key != 'applicant_id')){
                    $sql .=  $key. " = '$value',";
                }
        }
        $sql = substr($sql, 0, -1);
        $sql .= " WHERE ".$applicant_id." = $applicant_id";
        $result = mysql_query($sql,$db) or die(mysql_error(). "<br />SQL: $sql");   
    } 
} 
like image 908
PeggyMe Avatar asked Apr 28 '26 04:04

PeggyMe


2 Answers

The solution is to start with your known list of possible checkboxes in an array() or similar. Can I assume you generate the form with such a list? If not, you probably should. Then you can use a loop over the same data to check for the existence of each checkbox.

Some other hints:

isset($array[$key]) is not recommended. Although it will be reliable most of the time, it will fail if $array[$key] is null. The correct call is array_key_exists($key, $array).

When assembling string fragments for SQL, like you're doing, it is more elegant to do the following:

 $sqlvalues = array();
 foreach( $options as $field ) {
    if( array_key_exists('checkbox_'.$field, $_POST) )
        $sqlvalues[] = $field.' = \'on\'';
    else
        $sqlvalues[] = $field.' = \'off\'';
 }
 mysql_query('UPDATE '.$table.' SET '.implode(', ', $sqlvalues).' WHERE applicant_id = '.$applicant_id);
like image 124
staticsan Avatar answered Apr 29 '26 19:04

staticsan


You may be running to HTML checkbox behavior: Checkboxes are only sent to the server if they are on; if they are off, no name/value pair is sent. You are going to have trouble turning off values with the above code.

So you need to run through your known list of values and check for them in the $_POST parameters.

like image 25
ndp Avatar answered Apr 29 '26 17:04

ndp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!