MySQL Error Handling in PHP

MySQL query error message

The removed mysql_error() function returned the text of the most recent error from PHP's original MySQL extension. Current PDO and MySQLi applications should use exceptions for normal application flow and log technical details away from visitors.

Historical mysql_error()

<?php
// Historical only: removed from PHP 7+
$query = mysql_query('SELECT new_field FROM student');
echo mysql_error();
?>
Unknown column 'new_field' in 'field list'

PDO exception handling

<?php
try {
    $dbo = new PDO($dsn, $user, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);

    $stmt = $dbo->query('SELECT no_name FROM student');
} catch (PDOException $e) {
    error_log($e->getMessage());
    echo 'Database request failed.';
}
?>

PDO errorInfo()

If code is intentionally using a non-exception error mode, errorInfo() returns SQLSTATE, a driver-specific code, and the driver message.

<?php
$info = $stmt->errorInfo();
print_r($info);
?>
Array
(
    [0] => 42S22
    [1] => 1054
    [2] => Unknown column 'no_name' in 'field list'
)

MySQLi exceptions

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
    $result = $connection->query('SELECT no_name FROM student');
} catch (mysqli_sql_exception $e) {
    error_log($e->getMessage());
    echo 'Database request failed.';
}
?>
Do not display raw SQL errors, SQL text, credentials or stack traces to ordinary visitors on a production site. Log technical details server-side and return a generic message to the user.

Continue with SQLSTATE and database error codes or server-side error notification.

← 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