Skip to content
Advertisement

for each on post from form not submitting correctly

I am trying to loop thorough a form and submit the values to the database. It seems to work, except for that it tries to include the submit button itself into the database and so throws an error (as it doesnt exist in the DB) – it still submits the other data to the correct fields. I tried adding in an if statement to avoid submitting the submit button values, which does indeed remove it (as when I print to the results it doesn’t show and doesn’t throw the error), but it stops the other values submitting to the database. I tried the below:

foreach($_POST as $key =>$value){
    if($key!==='btnSubmit') {
$db->query($db->prepare("UPDATE `db-table` SET ".$key."= %s WHERE id= %d", $value, $selectedProduct));
}

Any ideas how to get around this is appreciated.

Advertisement

Answer

You can use inarray method to skip certain fields from the $_POST data as given below

$skipKeys = array(
                    'btnSubmit',
                    // add more fields if needed
                 );

foreach($_POST as $key =>$value){

        if(!in_array($key,$skipKeys)){
            $db->query(
                $db->prepare(
                "UPDATE `db-table` SET ".$key."= %s WHERE id= %d", $value, $selectedProduct
                )
            );
        }

}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement