views:

246

answers:

3

I have a BUNCH of $_POST variables being sent in via a long form and instead of hard coding each one with a mysql_escape_string() is it ok for me to do the following? I don't know if this is actually safe and/or viable code.

foreach ($_POST as &$post_item){
    $post_item = mysql_escape_string($post_item);
}

I'm fairly certain that because i'm using the &, it's passing it in by reference, not value, so i'm actually changing the value in the $_POST.

Also, should I use mysql_real_escape_string() instead?

EDIT: I am using PDO and prepare() along with the above method. Does this take care of it for me?

+10  A: 

Why not use array_map()?

array_map(mysql_real_escape_string, $_POST);

But in reality you should be using parametrized/prepared statements.

mysql_real_escape_string() takes the current database character set into account, mysql_escape_string() does not. So the former is the better alternative in comparison.

Edit (following up the OP's edit to the question):

Since you already do PDO prepared statements, there is no need to modify your values. PDO takes care of everything, that's the whole point of it (If you really put all data in parameters, that is - just concatenating strings to build SQL statements leads to disaster with PDO or without). Escaping the values beforehand would lead to escaped values in the database.

Tomalak
+3  A: 

Yes, you should be using mysql_real_escape_string(), if you're going to go that route. But the correct way to make sure the variables are safe to send to the database is using Parameterized Queries which are provided in PHP through either the mysqli functions or PDO.

Chad Birch
see edit, i am using pdo
contagious
+1  A: 

In addition to the previous comments, another benefit to using parameterised queries is that the database will be able to do better optimisations and probably use a cached query plan so you will get better performance.

1800 INFORMATION