2

How do I correctly write the code for a MySQL query that both implodes and mysql_real_escape_string?

This is the code that I have, but it's failing:

$sql = "INSERT INTO BEER_LOCATIONS 
        (LOCATION_NAME, LOCATION_STREET, LOCATION_CITY, LOCATION_STATE,
        LOCATION_ZIPCODE, LOCATION_PHONE, BEER_STYLE ) 
    VALUES 
        ('" . mysql_real_escape_string(implode("', '", $row)) . "')";

Thanks

2 Answers 2

13
implode("', '", array_map('mysql_real_escape_string', $row))

This applies mysql_real_escape_string to every element in $row and returns an array with the escaped values to implode.

Sign up to request clarification or add additional context in comments.

Comments

0

Even though this is a very old question, Google still brought me here, so maybe my solution will be helpful to someone else:

When trying to use the MySQLi version of mysql_real_escape_string, you'll realise that array_map can't handle the two parameters required for mysqli_real_escape_string. Hence you have to wrap it in a function that only takes one parameter:

function arrayEscaper($val){
   global $link;
   return mysqli_real_escape_string($link, $val);
 };

Then you can use that function in array_map like so:

$myArray = ["one", "two", "three"];
$myArrayEsc = array_map('arrayEscaper', $myArray);
$myString = implode(", ", $myArrayEsc);

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.