Article

Replacing mysql_real_escape_string

Remove mysql_real_escape_string() safely: lifecycle, modern replacements, and migration examples for legacy PHP apps.

mysql_real_escape_string() escaped a string for use in an SQL statement using the current charset of a mysql link. It was frequently misused as a general “sanitize everything” function and still allowed SQL logic bugs when quotes were mismanaged.

Lifecycle (php.net)

  • Deprecated: ext/mysql deprecated as of PHP 5.5.0
  • Removed: PHP 7.0.0

Modern replacement

Do not seek a 1:1 escape helper. Use prepared statements. For rare dynamic identifiers, maintain a strict allowlist—not string escaping.

Migration example

# LEGACY — mysql_real_escape_string()
$name = mysql_real_escape_string($_POST['name'], $link);
mysql_query("UPDATE users SET name='$name' WHERE id=$id", $link);

# MODERN
$stmt = $pdo->prepare('UPDATE users SET name = ? WHERE id = ?');
$stmt->execute([$_POST['name'], (int)$id]);

Scan before cutover

Search the tree for mysql_real_escape_string() and paste samples into the PHP Version Compatibility Checker and PHP Deprecated Checker.

Related tools

Related reading