18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Database Access<br />

Update queries<br />

Update queries look like a hybrid of Insert and Select statements. They consist<br />

of both fields to set on a table and conditions to restrict the query.<br />

db_update('imports')<br />

->condition('name', 'Chico')<br />

->fields(array('address' => 'Go West St.'))<br />

->execute();<br />

The condition() method works exactly like the condition() method of Select<br />

queries, and we can add multiple if we need to. fields() takes an associative array<br />

of values to set. The above query is therefore equivalent to:<br />

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

We still always want to use the dynamic approach rather than just call db_query(),<br />

because on some databases (such as PostgreSQL or Oracle) there are cases where<br />

the above query would not work and we would need to run multiple queries with<br />

bound values and other odd edge cases. All of that handling is handled for us<br />

automatically by the database layer.<br />

The return value from execute() for Update queries is the number of records that<br />

were changed by the query. Note that 'changed' does not mean 'matched'. If the<br />

WHERE portion of the query matches a record but if that record already has the values<br />

that it would be set to, it will not be changed and would not count towards the<br />

return value from execute().<br />

Delete queries<br />

Delete queries should come as no surprise, as they consist of essentially just a<br />

WHERE clause:<br />

db_delete('imports')<br />

->condition('name' => 'Zeppo')<br />

->execute();<br />

The return value from execute() for Delete query is the number of records that<br />

were deleted by the query.<br />

Merge queries<br />

Merge queries are one of the oft-forgotten parts of SQL. In part, that's because the<br />

most popular open source databases do not support them directly even though<br />

they are part of the SQL specification.<br />

[ 370 ]

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

Saved successfully!

Ooh no, something went wrong!