MySQL Error Codes in PHP

MySQL error code

The historical mysql_errno() function returned the numeric error code for the original MySQL extension. Current applications can work with SQLSTATE plus a driver-specific code.

Historical mysql_errno()

<?php
// Historical only: removed from PHP 7+
$query = mysql_query('SELECT new_field FROM student');
echo mysql_errno();
?>

An unknown column commonly produces MySQL driver error 1054, but application logic should not assume one hard-coded code covers every failure.

PDO SQLSTATE and driver code

<?php
$stmt = $dbo->prepare('SELECT * FROM nonexistence_table');

if (!$stmt->execute()) {
    $info = $stmt->errorInfo();
    echo 'SQLSTATE: ' . $info[0] . '<br>';
    echo 'Driver code: ' . $info[1];
}
?>
SQLSTATE: 42S02

PDO exceptions

<?php
try {
    $dbo->query('SELECT * FROM nonexistence_table');
} catch (PDOException $e) {
    echo htmlspecialchars($e->getCode(), ENT_QUOTES, 'UTF-8');
}
?>

MySQLi error number

<?php
try {
    $connection->query('SELECT no_name FROM student');
} catch (mysqli_sql_exception $e) {
    echo $e->getCode();
}
?>

Pair codes with safe error-message handling; codes are useful for logs and targeted recovery, while visitors should normally see a generic message.

← All PHP & MySQL topics




Subscribe to our YouTube Channel here



plus2net.com




SQL Video Tutorials










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer