function db_prefix_tables

You are here

4.6 database.inc db_prefix_tables($sql)
4.7 database.inc db_prefix_tables($sql)
5 database.inc db_prefix_tables($sql)
6 database.inc db_prefix_tables($sql)

Append a database prefix to all tables in a query.

Queries sent to Drupal should wrap all table names in curly brackets. This function searches for this syntax and adds Drupal's table prefix to all tables, allowing Drupal to coexist with other systems in the same database if necessary.

Parameters

$sql: A string containing a partial or entire SQL query.

Return value

The properly-prefixed string.

Related topics

8 calls to db_prefix_tables()
db_query in includes/database.pgsql.inc
Runs a basic query in the active database.
db_query in includes/database.mysql-common.inc
Runs a basic query in the active database.
db_query_range in includes/database.mysql.inc
Runs a limited-range query in the active database.
db_query_range in includes/database.mysqli.inc
Runs a limited-range query in the active database.
db_query_range in includes/database.pgsql.inc
Runs a limited-range query in the active database.

... See full list

File

includes/database.inc, line 81
Wrapper for database interface code.

Code

function db_prefix_tables($sql) {
  global $db_prefix;

  if (is_array($db_prefix)) {
    if (array_key_exists('default', $db_prefix)) {
      $tmp = $db_prefix;
      unset($tmp['default']);
      foreach ($tmp as $key => $val) {
        $sql = strtr($sql, array('{' . $key . '}' => $val . $key));
      }
      return strtr($sql, array('{' => $db_prefix['default'], '}' => ''));
    }
    else {
      foreach ($db_prefix as $key => $val) {
        $sql = strtr($sql, array('{' . $key . '}' => $val . $key));
      }
      return strtr($sql, array('{' => '', '}' => ''));
    }
  }
  else {
    return strtr($sql, array('{' => $db_prefix, '}' => ''));
  }
}

Comments

Because db_prefix_tables() always strips all curly braces from all queries, you cannot match field containing serialized data on substrings containing a curly brace.

A workaround is to use a placeholder:

db_query("SELECT uid FROM {users} WHERE name LIKE '%s'", '{foo');

Note that this escapes quotes in the placeholder data.

In Drupal 7 you can do this:

<?php
Database
::getConnection()->prefixTables($sql);
?>