Article

Replacing mysql_query

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

mysql_query() sent a SQL string through the obsolete ext/mysql extension and returned a result resource (or false). It encouraged interpolated SQL and had no native prepared-statement API.

Lifecycle (php.net)

  • Deprecated: ext/mysql deprecated as of PHP 5.5.0
  • Removed: PHP 7.0.0 (entire ext/mysql removed)

Modern replacement

Use PDO or mysqli with prepared statements. Prefer bound parameters over escaping.

Migration example

# LEGACY — mysql_query()
$res = mysql_query("SELECT name FROM users WHERE id=$id");
while ($row = mysql_fetch_assoc($res)) { echo $row['name']; }

# MODERN
$stmt = $pdo->prepare('SELECT name FROM users WHERE id = ?');
$stmt->execute([(int)$id]);
foreach ($stmt as $row) { echo $row['name']; }

Also migrate companion calls: mysql_connect, mysql_real_escape_string.

Scan before cutover

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

Related tools

Related reading