$ _POST as $ key => $ value using checkboxes

I'm having trouble getting a form to update the information passed from the checkbox. I was given this code.

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

This works fine as long as I call each checkbox separately. My problem is that I have about 200 flags.

Here is the code I'm using for UPDATEs. Can someone help me figure out where to paste the code that was entered into my real code? I tried all kinds of options.

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");   
    } 
} 
+3
source share
5 answers

, array() . , ? , , , . , .

:

isset($array[$key]) . , , $array[$key] null. array_key_exists($key, $array).

SQL, , :

 $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);
+5

, HTML checkbox: , ; , / . .

, $_POST.

+1

, PHP.

ndp, , . "off".

<label for="one">One</label> 
<input type="hidden" name="checkboxes[one]" value="off"/>
<input type="checkbox" name="checkboxes[one]" id="one" value="on"/>

checked = "checked", .

POST GET

foreach ($_POST['checkboxes'] as $key => $value) {
    //something
}
+1
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 ? 'on' : 'off') . "',";
                }
            }
            $sql = substr($sql, 0, -1);
            $sql .= " WHERE ".$applicant_id." = $applicant_id";
            $result = mysql_query($sql,$db) or die(mysql_error(). "<br />SQL: $sql");   
    } 
}

, - . , , .

By the way, your current code UPDATEis vulnerable to SQL injection because you do not deactivate your inputs with mysql_real_escape_string(). Greetings.

0
source

remove all of the above :-) name all the flags and in foreach work with $ _POST ['out'] BUT! do not forget the golden rule: do not believe the user. double-check each key => value before writing to the database.

0
source

Source: https://habr.com/ru/post/1716452/


All Articles