18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

[ 369 ]<br />

Appendix A<br />

The db_insert() method creates a new insert query object for the imports table.<br />

We then call the fields() method on that object. fields() takes an associative<br />

array of values to insert. In this case, we are adding a record for one of the world's<br />

great comedians. We then execute the query, causing it to be translated into the<br />

appropriate query string and executed. If there is an auto-increment or "serial" field<br />

in the imports table, the generated ID will be returned. That's all there is to it.<br />

db_insert() can get fancier, too. For instance, it supports multi-insert statements.<br />

To do that, we must first call fields() with an indexed array to specify what<br />

fields we are going to use and then call the values() method repeatedly with<br />

an associative array for each record.<br />

$values[] = array(<br />

'name' => 'Groucho',<br />

'address' => '123 Casablanca Ave.',<br />

'phone' => '555-1212',<br />

);<br />

$values[] = array(<br />

'name' => 'Chico',<br />

'address' => '456 Races St.',<br />

'phone' => '555-1234',<br />

);<br />

$values[] = array(<br />

'name' => 'Harpo',<br />

'address' => '789 Horn Ave.',<br />

'phone' => '555-1234',<br />

);<br />

$values[] = array(<br />

'name' => 'Zeppo',<br />

'address' => '22 University Way',<br />

'phone' => '555-3579',<br />

);<br />

$insert = db_insert('imports')->fields(array('name', 'address',<br />

'phone' => '555-1212'));<br />

foreach ($values as $value) {<br />

$insert->values($value);<br />

}<br />

$insert->execute();<br />

On databases that support multi-insert statements, the preceding code will be run as<br />

a single query. For those that don't, they will run as separate queries within a single<br />

transaction. That makes them extremely powerful and efficient for mass import<br />

operations. Note that in a multi-insert query the return value from execute() is<br />

undefined and should be ignored.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!