Fez Vrasta
Fez Vrasta

Reputation: 14825

Escape for DB entire Array

I'm using PHP to write a script that will give me a MySQL query that I will then use directly from MySQL Workbench.

I fetch the data from a .csv and then I loop them to write the SQL syntax with PHP.

My problem is a way to escape every string inside the array to prevent that I get a corrupted query.

How can I run mysqli_real_escape on an entire array?

Upvotes: 1

Views: 1356

Answers (2)

Achrome
Achrome

Reputation: 7821

First, try to use PDO instead. With prepared statements, your variables are sent separately from the query and you don't have to worry about manually escaping the parameters.

Second, if you REALLY need to do this, use mysqli_real_escape_string with array map. Something like this should work

$escapedArray = array_map(function($val) use ($mysqli) {
        return is_string($val) ? $mysqli->real_escape_string($val) : $val;
}, $unescapedArray);

Or procedurally like this

$escapedArray = array_map(function($val) use ($mysqli) {
        return is_string($val) ? mysqli_real_escape_string($mysqli, $val) : $val;
}, $unescapedArray);

The reason for this is simple. If any element of the array is not a string, escaping it will return null, so you return the element as is.

EDIT: For nested arrays, you will have to use array_walk_recursive, instead of array_map.

array_walk_recursive($varArray, function(&$val) use($mysqli) {
    $val = !is_string($val) ?: mysqli_real_Escape_string($mysqli, $val);
});

Upvotes: 4

Clart Tent
Clart Tent

Reputation: 1309

You could use array_map. Something like:

$safeArray = array_map ('mysqli_real_escape_string', $originalArray);

Upvotes: 2

Related Questions