9951 explained code solutions for 126 technologies


php-mysqlHow to escape a string for MySQL in PHP?


The best way to escape a string for MySQL in PHP is to use the mysqli_real_escape_string() function. This function takes two parameters, the first being the MySQL connection and the second being the string to be escaped.

$conn = mysqli_connect("localhost", "username", "password", "database");
$escapedString = mysqli_real_escape_string($conn, $string);

The output of the above code will be the escaped string.

The mysqli_real_escape_string() function does the following:

  • Escapes special characters in the string for use in an SQL statement
  • Adds backslashes before characters that need to be escaped
  • Prepares the string for use in a MySQL query

Helpful links

Edit this code on GitHub