Created
November 11, 2015 18:36
-
-
Save cesarmiquel/093aacbca0138791ef03 to your computer and use it in GitHub Desktop.
Example calls to D7 database API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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