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.
<?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);
}
?>
<?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');
}
?>
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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.