This is a small segment, that is built using PHP and database for for simplicity and testing purposed, here is a text example.
The idea is the form will submit, then PHP will handle results. However I am trying to use mysql_real_escape_string for each post for security (maybe there is a better way?)
Anyways, here is the problem. When I keep the foreach loop in place, the two post array variables of qty[] and optname[] both come back as NULL (outputted via the var_export($_POST) for testing purposes. This is what outputs WITH foreach mysql_real_escape_string loop:
array (
'update' => 'Yes',
'qty' => NULL,
'optname' => NULL,
)
If I remove the foreach loop everything works fine, this is what I get and is what I need for php to process results, this is what I get with foreach mysql_real_escape_string loop commented out:
array (
'update' => 'Yes',
'qty' =>
array (
1 => '2',
2 => '2',
3 => '2',
4 => '2',
),
'optname' =>
array (
1 => '1|4',
2 => '1|4',
3 => '1|4',
4 => '1|4',
),
)
But the data is not being checked/cleaned before sql queries occur. How can I check each post variable using a loop but keep the POST variables intact??
Here is the code that can be pasted in any local host and tested.
<?php
foreach ($_POST as $key=>$value) { $_POST[$key] = mysql_real_escape_string($value); }
echo '<pre>';
var_export($_POST);
echo '</pre>';
?>
<form name="updateQty" id="updateQty" method="post" />
<input type="hidden" name="update" id="update" value="Yes" />
<input type="text" name="qty[1]" id="qty[]" class="field" value="2" />
<input type="hidden" name="optname[1]" id="optname[]" value="1|4" />
<input type="text" name="qty[2]" id="qty[]" class="field" value="2" />
<input type="hidden" name="optname[2]" id="optname[]" value="1|4" />
<input type="text" name="qty[3]" id="qty[]" class="field" value="2" />
<input type="hidden" name="optname[3]" id="optname[]" value="1|4" />
<input type="text" name="qty[4]" id="qty[]" class="field" value="2" />
<input type="hidden" name="optname[4]" id="optname[]" value="1|4" />
<input type="submit">
</form>
Thanks!
foreach ($_POST as $key=>$value) {
if(is_array($value)){
foreach ($value as $k => $v) {
$_POST[$key][$k] = mysql_real_escape_string($v);
}
} else {
$_POST[$key] = mysql_real_escape_string($value);
}
}
In your case your POST values are arrays so you must loop them too..
As @hjpotter92 comment its not good to use old mysql functions. They wont work in future versions...