Skip to content

Instantly share code, notes, and snippets.

@cesarmiquel
Created November 11, 2015 18:36
Show Gist options
  • Save cesarmiquel/093aacbca0138791ef03 to your computer and use it in GitHub Desktop.
Save cesarmiquel/093aacbca0138791ef03 to your computer and use it in GitHub Desktop.
Example calls to D7 database API
<?php
// Query and loop over results
$result = db_select('node', 'n')
->fields('n', array('nid'))
->condition('type', 'article')
->condition('uid', array(0,1), 'IN')
->execute();
foreach($result as $row) {
// process row
print $row->nid;
}
// Another way to query and loop over results. The first
// one is the recommended for new code.
$result = db_query("SHOW TABLES");
if ($result) {
while ($row = $result->fetch(PDO::FETCH_NUM)) {
// process each row
// ..
}
}
// Execute a query that counts
$number_of_rows = db_select('node')
->countQuery()
->execute()
->fetchField();
// Execute a query that retrieves a single column
// from a single row:
$number_of_rows = db_select('users', 'u')
->fields('u' ,array('name'))
->condition('uid', 1)
->execute()
->fetchField();
// Execute a single query disregarding results
db_query("RENAME TABLE {$table_old} TO {$table_new}");
// More examples here: https://www.drupal.org/developing/api/database
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment