A.4. Database Interaction

What's a web application framework without a Database API? Not much! Drupal's Database API is undergoing a rewrite for Drupal 7, which will probably be released in 2009, but even in the new version, it is likely that this guide will be useful. These functions were originally covered in Chapter 5.

  • db_query("SELECT name FROM {user} WHERE mail = %s", $tainted)

    • Description Filters data as it is added to database queries and then runs the query against the database.

    • Use Querying the database safely.

    • Example Inserting a record into the blocked IP list in user_block_ip_action in user.module.

    function user_block_ip_action() {
      $ip = ip_address();
      db_query("INSERT INTO {access} (mask, type, status) VALUES ('%s', '%s', %d)",
        $ip, 'host', 0);
    
     watchdog('action', 'Banned IP address %ip', array('%ip' => $ip));
    }
  • db_query_range()

    • Description Runs a query that returns a specific range of records such as the first 10 or the 20th to the 30th records.

    • Use Return a subset of the total records.

    • Example Providing a list of users for the username autocompletion widget in user.pages.inc.

    function user_autocomplete($string = '') {
      $matches = array();
    
      if ($string) {
        $result = db_query_range("SELECT name FROM {users} WHERE LOWER(name)
            LIKE LOWER('%s%%')", $string, 0, 10);
        while ($user = db_fetch_object($result)) {
          $matches[$user->name] = check_plain($user->name);
        }
      }
      drupal_json($matches);
    }
  • db_escape_table($table_name)

    • Description Filters a string to be used as a table or column name in ...

Get Cracking Drupal®: A Drop in the Bucket now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.