Search code examples
phpvariablesmysql-real-escape-string

Mysql real escape string loop multiple variables


Say I want to insert into name, address, city, state, zip values $name, $address Etc.....

How can I run mysql_real_escape_string on each of the variables before inserting. There has got to be a foreach or loop or while method instead of writing out each variable right?

Thanks for the help.

Tom

so if I have

 $data = array($address, $city, $name);
 array_map('mysql_real_escape_string', $data);

and

$columns = "name, address, city, state, zip";
$count = $dbh->exec("INSERT INTO customer($columns) VALUES ($data)");

I get a ton of errors.

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'root'@'localhost' (using password: NO) in /Users/tommyscott45/Sites/experiment/result.php on line 23

now what?


Solution

  • A database error has occurred when trying to invoke mysql_real_escape_string and I see that you're using $dbh->exec() to execute the query. This suggests that you connect to the database with PDO, so you should rather use PDO::quote instead of mysql_real_escape_string.

    Moreover, as others have already mentioned, a better way to solve your problem would be to use prepared statements and PDO::prepare.