I'm not sure if this is a bug or the intended behaviour :
db_table_exists(NULL) or db_table_exists(empty string) return the number of tables in the database.

Yet you'd expect code like the following would prevent you from errors :

if (db_table_exists($var)) {
  db_query('SELECT FROM {'. $var .'} WHERE ...');
}
Support from Acquia helps fund testing for Drupal Acquia logo

Comments

yched’s picture

That's with MySQL 4.1, btw

yched’s picture

Status: Active » Needs review
FileSize
1.26 KB

Actually I think it's a bug.
It does not match the function description, and I don't think the pgsql equivalent behaves the same (it uses a "WHERE name = $tablename" style construct.

Attached patch checks if the provided name is empty and returns 0. (usual PHP 'empty' stuff : it will also reject '0', which I think is not a valid table name anyway - could be fixed, but I did not want to add too much cruft)

It do not think this is baby sitting broken code either :

if (db_table_exists($var)) {
  // query the $var table being confident that it exists
}

cannot be considered broken code IMO, and should be considered 'the right way'

bdragon’s picture

How about this?

return (db_num_rows(db_query("SHOW TABLES LIKE '{" . db_escape_table($table) . "}'")) == 1);
drumm’s picture

Version: 5.x-dev » 6.x-dev
Status: Needs review » Needs work

If you want to return FALSE, then return that and not the number 0.

kbahey’s picture

Status: Needs work » Needs review
FileSize
2.2 KB

Here is a patch to mysql, mysqli, and pgsql.

It checks that $table is indeed passed in, and if so, it executes the query, otherwise it returns FALSE;

keith.smith’s picture

Status: Needs review » Needs work

patch no longer applies

# patch -p0 < db_table_exists_1.patch
patching file includes/database.mysqli.inc
Hunk #1 FAILED at 398.
1 out of 1 hunk FAILED -- saving rejects to file includes/database.mysqli.inc.rej
patching file includes/database.mysql.inc
Hunk #1 FAILED at 418.
1 out of 1 hunk FAILED -- saving rejects to file includes/database.mysql.inc.rej
patching file includes/database.pgsql.inc
Hunk #1 FAILED at 391.
1 out of 1 hunk FAILED -- saving rejects to file includes/database.pgsql.inc.rej

dpearcefl’s picture

Is there any interest or a need for this this be fixed?

Status: Needs work » Closed (outdated)

Automatically closed because Drupal 6 is no longer supported. If the issue verifiably applies to later versions, please reopen with details and update the version.