Home  >  Article  >  Backend Development  >  Commonly used database operation examples in Drupal7_PHP tutorial

Commonly used database operation examples in Drupal7_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:37:01775browse

1. Insert a single record

Copy code The code is as follows:
db_insert("table")->fields(array( 'field1' => 'value1', 'field2' => 'value2', 'fieldn' => $valuen))->execute();

2. Insert multiple records

Copy code The code is as follows:
$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. Update a certain record

Copy code The code is as follows:
db_update('imports')
->condition('name', 'Chico' )
->fields(array('address' => 'Go West St.'))
->execute();
//Equivalent to:

UPDATE {imports} SET address = 'Go West St.' WHERE name = 'Chico';


4. Delete a record

Copy code The code is as follows:
db_delete('imports')
->condition('name' => ' Zeppo')
->execute();

5. Merge records

Copy code The code is as follows:
db_merge('people')
->key(array('job' => ; 'Speaker'))
->insertFields(array('age' => 31,'name' => 'Meredith'))
->updateFields(array('name' => ; 'Tiffany'))
->execute();
//If there is a record with job as Speaker, update the name to Tiffany, if it does not exist, insert a record with age 31 and name Meredith , job is the record of Speaker.

6. Automatically add one or self-increment to a certain field value in the database.

Copy code The code is as follows:
db_update('example_table')
->expression('count', 'count + 1')
->condition('field1', $some_value)
->expression('field2', 'field2 + :inc', array(':inc' => 2))
->execute();

7. Query a certain field in the database for another alias

Copy code The code is as follows:
$query = db_select('node', 'n');
$query-> ;addField('n', 'name', 'label');
$query->addField('n', 'name', 'value');

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/736824.htmlTechArticle1. Insert a single record and copy the code as follows: db_insert("table")-fields(array('field1' = 'value1', 'field2' = 'value2', 'fieldn' = $valuen))-execute(); 2. Insert multiple records and copy code...
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