dbtng_example_entry_load

  1. drupal
    1. 7 dbtng_example.module function
Drupal 7 dbtng_example_entry_load($entry = array())

Read from the database using a filter array.

In Drupal 6, the standard function to perform reads was db_query(), and for static queries, it still is.

db_query() used an SQL query with placeholders and arguments as parameters.

 // Old way
 $query = "SELECT * FROM {dbtng_example} n WHERE n.uid = %d AND name = '%s'";
 $result = db_query($query, $uid, $name);

Drupal 7 DBTNG provides an abstracted interface that will work with a wide variety of database engines.

db_query() is deprecated except when doing a static query. The following is perfectly acceptable in Drupal 7. See the handbook page on static queries

  // SELECT * FROM {dbtng_example} WHERE uid = 0 AND name = 'John'
  db_query(
    "SELECT * FROM {dbtng_example} WHERE uid = :uid and name = :name",
    array(':uid' => 0, ':name' => 'John')
  )->execute();

But for more dynamic queries, Drupal provides the db_select() API method, so there are several ways to perform the same SQL query. See the handbook page on dynamic queries.

  // SELECT * FROM {dbtng_example} WHERE uid = 0 AND name = 'John'
  db_select('dbtng_example')
    ->fields('dbtng_example')
    ->condition('uid', 0)
    ->condition('name', 'John')
    ->execute();

Here is db_select with named placeholders:

  // SELECT * FROM {dbtng_example} WHERE uid = 0 AND name = 'John'
  $arguments = array(':name' => 'John', ':uid' => 0);
  db_select('dbtng_example')
    ->fields('dbtng_example')
    ->where('uid = :uid AND name = :name', $arguments)
    ->execute();

Conditions are stacked and evaluated as AND and OR depending on the type of query. For more information, read the conditional queries handbook page at: http://drupal.org/node/310086

The condition argument is an 'equal' evaluation by default, but this can be altered:

  // SELECT * FROM {dbtng_example} WHERE age > 18
  db_select('dbtng_example')
    ->fields('dbtng_example')
    ->condition('age', 18, '>')
    ->execute();

Parameters

$entry: An array containing all the fields used to search the entries in the table.

Return value

An object containing the loaded entries if found.

See also

db_select()

db_query()

http://drupal.org/node/310072

http://drupal.org/node/310075

Related topics

5 calls to dbtng_example_entry_load()

File

sites/all/modules/examples/dbtng_example/dbtng_example.module, line 246
This is an example outlining how a module can make use of the new DBTNG database API in Drupal 7.

Code

function dbtng_example_entry_load($entry = array()) {
  // Read all fields from the dbtng_example table.
  $select = db_select('dbtng_example', 'example');
  $select->fields('example');

  // Add each field and value as a condition to this query.
  foreach ($entry as $field => $value) {
    $select->condition($field, $value);
  }
  // Return the result in object format.
  return $select->execute()->fetchAll();
}