Logging and Reporting MySQL Errors

MySQL error notification

The original tutorial mailed raw mysql_error() output after a failed query. Modern applications should avoid exposing or blindly emailing complete database errors because messages can contain sensitive SQL or environment details.

Historical error-mail pattern

<?php
// Historical only: removed from PHP 7+
$query = mysql_query('SELECT no_field FROM student');
if (!$query) {
    $errorMessage = mysql_errno() . ' - ' . mysql_error();
    mail('programmer@example.com', 'Database error', $errorMessage);
}
?>

Preferred pattern: log server-side

<?php
try {
    $stmt = $dbo->prepare(
        'SELECT id, name FROM student WHERE id = :id'
    );
    $stmt->execute(['id' => 1]);
} catch (PDOException $e) {
    $reference = bin2hex(random_bytes(6));
    error_log(
        'DB error [' . $reference . '] SQLSTATE ' . $e->getCode()
    );
    echo 'Database request failed. Reference: ' . htmlspecialchars($reference, ENT_QUOTES, 'UTF-8');
}
?>

Optional notification email

If email alerts are appropriate for your application, send a short sanitized reference rather than credentials, full SQL, or a complete stack trace:

<?php
$subject = 'Database error reference ' . $reference;
$body = 'Check the server log for reference ' . $reference;
mail('programmer@example.com', $subject, $body);
?>

See PHP mail(), PHP if/else, database error handling, and error codes.

← 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