Applying mysql_real_escape_string to a whole array

Ok, here’s an easy one, I want to apply mysql_real_escape_string to all the elements in an array so that I can use them already escaped without having to do so explicitly to each one.

So, for example, the elements are like so:

mysql_real_escape_string($entryArray["title"])
mysql_real_escape_string($entryArray["duration"])

… etc

Now, here is where it gets tricky, the array is a multidimensional array like so:

array(30) {
[“dateAdded”]=>
float(1092337200)
[“media”]=>
string(3) “DVD”
[“lentHistory”]=>
array(1) {
[0]=>
array(2) {
[“name”]=>
string(6) “Noelle”
[“date”]=>
float(1109707200)
}
}
[“videoFormat”]=>
string(4) “NTSC”
}

so I had this code:

foreach ($entryArray as $escapee)
		 {
		 	$escapedArray .= mysql_real_escape_string($escapee);
		 }

which doesn’t work because mysql_real_escacpe_string expects a string, not an array.

Any simple ideas :smiley:

From manual, function array_map:

<?php

function multidimensionalArrayMap( $func, $arr )
    {
    $newArr = array();
    foreach( $arr as $key => $value )
        {
        $newArr[ $key ] = ( is_array( $value ) ? multidimensionalArrayMap( $func, $value ) : $func( $value ) );
        }
    return $newArr;
    }

?>

And this question belongs to main PHP forum, not to Application Design.

Have you tried using [COLOR=Black]array_walk_r[/COLOR]ecursive on the array in conjunction with mysql_real_escape_string?

array_walk_recursive sounds promising, the manual says this is the usage:

bool array_walk_recursive ( array &$input , callback $funcname [, mixed $userdata ] )

so my code is this:

function escapeMe($val) {
		 	mysql_real_escape_string($val);
		 }
		
		array_walk_recursive(&$entryArray, 'escapeMe');

If you pass the array by reference it’s supposed to change the original array, but it’s not doing it so not sure how to apply it here.

You need to make your callback function assign the modified value to the item (which needs to be passed to the function by reference.

function escapeMe(&$val) {
    $val  = mysql_real_escape_string($val);
}

P.S. I would advise against the blunderbuss approach of applying the escaping to every item in the array. Such “protection” leaves much to be desired.

Also remove the & from your function call. It (&) has to be there in function definition .

It should be

array_walk_recursive($entryArray, 'escapeMe'); //no & in $entryArray
function escapeMe(&$val) {                //& in $val
    $val  = mysql_real_escape_string($val);
} 

Refer this for proper syntax.

Why continue to use “mysql_*” escape functions in the first place.
Upgrade to 2010 and use Prepared Statements.

Thanks for all the suggestions, I’ll try them.

What are “Prepared Statements”?

http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html

Prepared statements can help increase security by separating SQL logic from the data being supplied. This separation of logic and data can help prevent a very common type of vulnerability called an SQL injection attack.

Ah yes, I’ve read about these but seemed impractical when I tried to use them in the real world. Will have to take another look.

It is practical most of the time. It is only when you have a parameter for something that can’t be substituted into the query (such as a table name) that you can’t do it for that particular parameter.

The way the Mysql cookbook explained it it was useful for recurring queries because you have a prepared statement that you only change the values you want. For a single query (which is what this is) it seemed a waste of code to me. Of course, I didn’t know it would also take care of escaping characters.

Honestly though, for a sinlge query it still seems like a waste of code unless I’m missing some other magic of Prepared Statements.

The query you use is stored in MySQLs memory a lot longer then the script itself. While it may be used in the script once, it is used in multiple instances of that script. Prepared Statements transcend PHP instances. Furthermore, making SQL Injection almost impossible, making the above “escaping” code obsolete.

Prepared Statements are very practical even for single SQL queries. There is actually less code for Prepared Statements, the actual work is done on the SQL server instead. (If it supports Prepared Statements of course.)

If you don’t want to use Prepared Statements, at least use the MySQLi extension instead of the older set.

That’s interesting, I didn’t know that, none of this was mentioned in the cookbook nor did I see it in the links you sent, but I did read them on my iphone this morning before coffee so maybe I just missed them. :smiley:

While we’re on the subject, what is the difference between Mysqli and mysql connectors?

Around the middle of the page: http://us2.php.net/manual/en/mysqli.overview.php

Well, this is a whole new box of frogs. Having started with php and mysql many, many moons ago I stayed with the old ways and have been slow to update (never mind that I forgot a lot of stuff in the interim :slight_smile:

But this looks really interesting, will try to incorporate it into this current project.

Once again, thank you very much to all who helped, this forum is invaluable.

Stay tuned for some more pestering questions about mysqli now :smiley:

Trying to apply this to my current project and running into a problem.

A tutorial I found says that to get results with prepared statements you need to do this:

/* bind variables to prepared statement */
    $stmt->bind_result($col1, $col2); 

does that mean I have to list each and every column I want? That’s evil. Whatever happened to a good ol’ associative array? Can we not use those with prepared statements?

DO NOT use mysqli barebone, thats about the worst way to do prepared statements. Use PDO Mysql or a Mysqli wrapper, that has prepare statements in it and much easier interface.

I wrote a mysqli wrapper, which is now integrated with the company I work for and only supports 5.3, but you can use the older version (for 5.2) at http://gorilla3d.com/v8/wiki/doku.php?id=mysqli_db. If you do have 5.3 just PM me and I’ll send you the updated file.

Oh boy :rolleyes:

any tutorials on PDO?

Here is a good rant on both if you really want to pick your mind: http://stackoverflow.com/questions/13569/mysqli-or-pdo-what-are-the-pros-and-cons

As far as a tutorial:

Thats a great introduction to PDO.