Posted in PHP onMarch 02, 2014
1.插入单条记录
db_insert("table")->fields(array('field1' => 'value1', 'field2' => 'value2', 'fieldn' => $valuen))->execute();
2.插入多条记录
$values[] = array('field1' => 'val1', 'field2' => 'val2', 'fieldn' => $valn); $values[] = array('field1' => 'value1', 'field2' => 'value2', 'fieldn' => $valuen); $query = db_insert(‘table')->fields(array('field1', 'field2', 'fieldn')); foreach ($values as $record) { $query->values($record); } $query->execute();
3.更新某条记录
db_update('imports') ->condition('name', 'Chico') ->fields(array('address' => 'Go West St.')) ->execute(); //等同于: UPDATE {imports} SET address = 'Go West St.' WHERE name = 'Chico';
4.删除某条记录
db_delete('imports') ->condition('name' => 'Zeppo') ->execute();
5.合并记录
db_merge('people') ->key(array('job' => 'Speaker')) ->insertFields(array('age' => 31,'name' => 'Meredith')) ->updateFields(array('name' => 'Tiffany')) ->execute(); //如果存在job为Speaker的一条记录,则更新name为Tiffany,如果不存在,就插入一条age为31,name为Meredith,job为Speaker的记录。
6.对数据库某字段值自动加一或者自增。
db_update('example_table') ->expression('count', 'count + 1') ->condition('field1', $some_value) ->expression('field2', 'field2 + :inc', array(':inc' => 2)) ->execute();
7.查询数据库某字段为另一别名(alias)
$query = db_select('node', 'n'); $query->addField('n', 'name', 'label'); $query->addField('n', 'name', 'value');
Drupal7中常用的数据库操作实例
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@