Rather than running a conditional check on every iteration of the $_POST
array, better practice would be to filter $_POST
before looping, then you can use your prepared statement query (for security reasons) on every iteration without any conditional expressions.
It seems from your sample input that you are expecting either empty values or numeric values. Also, it is very common for database table structures to use auto-incremented id
's that start from 1
. I'll provide 3 different methods, so that you can choose the most effective one for your project. All methods preserve the original key (id
) in $_POST
after filtering.
Method #1: (remove all null, empty, false-y, zero-ish elements from $_POST
)
foreach(array_filter($_POST) as $id=>$value){
// insert your prepared statement query code block here
}
Method #2: (only permit elements from $_POST
with a value greater than zero)
foreach(array_filter($_POST,function($v){return $v>0;}) as $id=>$value){
// insert your prepared statement query code block here
}
Method #3: (only permit elements from $_POST
with a value that is an integer)
foreach(array_filter($_POST,function($v){return is_int($v);}) as $id=>$value){
// insert your prepared statement query code block here
}
Here is a demonstration of all three methods.
Furthermore, there are some unnecessary checks in Sahil's answer.
First, checking if(is_array($_POST))
will always give a true
result because $_POST is a superglobal array. If you don't believe me, you can trust deceze's comment here as he's got one of those fancy diamonds after his username. The exception being if you are using Content-Type:text/xml
, but surely that is not the case this time.
Second, checking the count()
on $_POST
is unnecessary as the foreach()
loop will not even iterate once if the array is empty.