I would like to do mysql real escape on all my posted forms found in the $_POST[] array. But I don't know how to loop through the array to escape every string.
I have different names like, serverAddressIn and serverPortOut that I need to "secure" before inserting them into the database.
How can I loop through my array and secure my form posts?
I want to mysqli_real_escape on all inputs before I handle them.
Nope, you don't.
to clean the strings
"mysqli_real_escape" doesn't "clean" anything.
Is there a better way
Sure. You have to use prepared statements. And, some sort of abstraction library to do all the dirty job for you. Here is an example using safeMysql:
include 'safemysql.class.php';
$db = new safeMysql();
$allowed = array('server', 'serverAddress', 'serverportIN', 'serverAddressOut');
$data = $db->filterArray($_POST, $allowed);
$sql = "INSERT INTO ?n SET ?u";
$db->query($sql, $table, $data);
as simple as that.
Note that you ought to make an explicit white list of your field names due to security reasons
Sample form
, escape
and query
<form method="POST">
<input name="options[name]" />
<input name="options[city]" />
<input type="submit" value="submit" />
</form>
<?php
if (isset($_POST) && !empty($_POST['options']))
{
foreach ($_POST['options'] as $key => $value)
{
$options[$key] = mysqli_real_escape_string($con, $value);
}
$query = "INSERT INTO table_name (`".implode("`, `", array_keys($options))."`) VALUES ('".implode("', '", $options)."')";
}
?>