Home >Backend Development >PHP Tutorial >Drupal7中常用的数据库操作实例_PHP

Drupal7中常用的数据库操作实例_PHP

WBOY
WBOYOriginal
2016-06-01 11:56:22852browse

Drupal

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');

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn