MySQL

Escape special characters

To escape special characters in a PHP string, you can use the backslash \ followed by the character you want to insert. For example \$ for a dollar sign to prevent variable interpolation.

Other examples:

  • \\ for a backslash
  • \' for a single quote
  • \" for a double quote
  • \n for a new line
  • \r for a carriage return
  • \t for a tab

Escaping special characters with mysqli_real_escape_string() for a posted value:

$user_last_name = mysqli_real_escape_string($conn, $_POST['user_last_name']);

Using mysqli_real_escape_string() (for MySQL queries)

$connection = new mysqli("server", "user", "password", "database");

$string = "O'Reilly's books";
$escaped_string = mysqli_real_escape_string($connection, $string);

$query = "SELECT * FROM books WHERE author = '$escaped_string'";
echo $query;