Примеры запросов к БД для Drupal 6 и Drupal 7.
Получить единственное значение поля (выборка с условиями)
// Drupal 6 $value = db_query("SELECT nid FROM {node} WHERE uid = %d AND type = '%s'", 5, 'page'); // Drupal 7 $value = db_query("SELECT nid FROM {node} WHERE uid = :uid AND type = :type", array( ':uid' => 5, ':type' => 'page', ))->fetchField();
Обход полученных записей
// Drupal 6 $result = db_query("SELECT * FROM {table}"); while ($row = db_fetch_object($result)) { /* ... */ } // Drupal 7 $result = db_query("SELECT * FROM {table}"); foreach ($result as $row) { /* ... */ }
Обновление записи:
// Drupal 6 db_query("UPDATE {node} SET title='%s', status=%d WHERE uid=%d", 'hello world', 1, 5); // Drupal 7 db_update('node')->fields(array('title' => 'hello world', 'status' => 1))->condition('uid', 5)->execute();
Удаление записи:
// Drupal 6 db_query("DELETE FROM {node} WHERE uid=%d AND created < %d", 5, time() - 3600); // Drupal 7 db_delete('node')->condition('uid', 5)->condition('created', time() - 3600, '<')->execute();
Добавление данных
// Drupal 6 db_query("INSERT INTO {mytable} (intvar, stringvar, floatvar) VALUES (%d, '%s', %f)", 5, 'hello world', 3.14); $id = db_last_insert_id(); // Drupal 7 $id = db_insert('mytable')->fields(array( 'intvar' => 5, 'stringvar' => 'hello world', 'floatvar' => 3.14, ))->execute();