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.

Database Access<br />

Finally we execute the query. execute() takes the information we have provided,<br />

runs the query through alter hooks if necessary, compiles the corresponding SQL<br />

string, and runs the query, returning a result object. The result object is the same as<br />

that returned from a static query.<br />

Also note that most methods of the select builder return the select object itself and<br />

thus are chainable. The exceptions are the addField() and join() methods, as those<br />

need to return a generated alias instead. The above query could therefore also have<br />

been written as:<br />

$query = db_select('node', 'n');<br />

$u_alias = $query->innerJoin('users' ,'u', '%alias.uid = n.uid');<br />

$query->addField($u_alias, 'name', 'username');<br />

$result = $query<br />

->fields('n', array('nid, title'));<br />

->condition("{$u_alias}.name", 'Bob');<br />

->condition('n.created', REQUEST_TIME - 604800, '>=');<br />

->orderBy('n.created', 'DESC');<br />

->range(0, 5);<br />

->addTag('node_access')<br />

->execute();<br />

The query builder is capable of building far more complex queries, too, including<br />

subselects, complex AND and OR conditions, among others. See the online<br />

documentation for the full details.<br />

Insert queries<br />

While SELECT queries have both static and dynamic versions, INSERT, UPDATE,<br />

DELETE, and MERGE queries only support a dynamic version. That is necessary in<br />

order to support the full range of SQL databases in the wild, many of which require<br />

extra special handling for some field types. As a nice bonus, the dynamic version of<br />

these queries is often much easier to work with than the static version would be and<br />

makes it easy to add additional database-specific optimizations. We'll look at Insert<br />

queries first.<br />

Just as with Select queries, Insert queries start with a constructor function and are<br />

chainable. In fact, all methods of Insert queries are chainable.<br />

$id = db_insert('imports')<br />

->fields(array(<br />

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

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

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

))<br />

->execute();<br />

[ 368 ]

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

Saved successfully!

Ooh no, something went wrong!