Normal Select queries:
----------------------
// Drupal 6
$result = db_query("SELECT nid, title FROM {node} WHERE uid = %d AND type = '%s'", 5, 'page');
// Drupal 7
$result = db_query("SELECT nid, title FROM {node} WHERE uid = :uid AND type = :type", array(
':uid' => 5,
':type' => 'page',
));
?>
Iterating a result set from db_query()
-------------------------------------
// Drupal 6
while ($record = db_fetch_object($result)) {
// Do stuff with $record, which is an object
}
// Drupal 7
foreach ($result as $record) {
// Do stuff with $record, which is an object
}
?>
Insert statements
-----------------
// 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();
?>
Update statements
-----------------
// 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();
?>
Delete statement
----------------
// Drupal 6
db_query("DELETE FROM {node} WHERE uid=%d AND created < %d", 5, REQUEST_TIME - 3600);
// Drupal 7
db_delete('node')
->condition('uid', 5)
->condition('created', REQUEST_TIME - 3600, '<')
->execute();
?>
Thanks for sharing the differnce between drupal 6 and drupal 7.
ReplyDeleteThanks Nice Job
ReplyDeleteThank You!! It's nice and clean and that helps a lot.
ReplyDelete