The function db_error() doesn't work if you try to get the latest error on the default connection.
Here's some code to reproduce the issue:
<?php
include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$result = db_query("SELECT unknown_field FROM {node}");
print "Error: ".db_error()."\n"; // db_error() always returns 0 but should return 1054 in case of MySQL
?>
The reason for this is that in case of a database error this error is reported via trigger_error(...). Drupal's error handler than calls watchdog(...) with an translated error message. Normally both SQL statements triggered by the translation using t(...) and the insert into the watchdog table don't fail. So the last SQL statement has no error and that's what db_error() returns!
A possible solution is to handle translations and watchdog entries via a dedicated connection.
Another workaround for command line scripts like cron.php is to define another error handler that doesn't trigger watchdog entries but prints out errors.
| Comment | File | Size | Author |
|---|---|---|---|
| #4 | db-error.patch | 4.38 KB | vgarvardt |
Comments
Comment #1
drummThe error should be stored in a static variable in db_error(), which would be set when the error happens.
Bumping priority down since this API is not used much.
Comment #2
pukku commentedThis still seems to be a problem in Drupal 6-14. It does make it difficult to determine if something went wrong.
Comment #3
OmarQot commentedI see this is critical, since there is no other way to handle db errors in drupal. if error occur then you continue the normal process which is really bad.
Comment #4
vgarvardt commentedPlease check this patch. I made changes to MySQL, MySQLi and PgSQL, but tested only with MySQL(i).
Comment #6
vgarvardt commentedCan you tell me how to create patch correctly? As I run this patch from Drupal root dir and it applies. Patch tester runs patch from sites/default/files/review
Comment #7
mkalkbrenner#298768: Ensure that entries are written to watchdog table solves this issue.