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 />

Basic queries<br />

Most SELECT queries are, in practice, fairly simple and do not change. <strong>Drupal</strong> calls<br />

these static queries, and they are very straightforward to use.<br />

For example, to get a list of all enabled modules in the system, we could run the<br />

following query:<br />

$result = db_query("SELECT name, filename FROM {system} WHERE type =<br />

:type AND status = :status", array(':type' => 'module', ':status' =><br />

1));<br />

In practice, if we wanted to get that information we would simply<br />

call module_list() instead, but for the purposes of this example<br />

we'll do it the manual way.<br />

The query looks very much like normal SQL that we would expect to see anywhere<br />

else, but there are a few important items to mention.<br />

• All SQL table names are wrapped in curly braces. That identifies the string<br />

as a table name to the database layer and allows <strong>Drupal</strong> to easily add a<br />

configured prefix to all tables for a given <strong>Drupal</strong> instance.<br />

• There is no MySQL-specific syntax (or any database-specific syntax)<br />

anywhere in the query.<br />

• There are no literal values in the query. Instead, literal values are specified by<br />

placeholders. Values for placeholders are specified in an associative array as<br />

the second parameter to db_query().<br />

Those placeholders are significant. They allow us to separate the query from the<br />

values in the query and pass them to the database server separately. The database<br />

server can then assemble the query string and placeholder values as needed, with<br />

full knowledge of what data type makes sense in each case. That eliminates most<br />

(although not quite all) opportunities for SQL injection from unexpected data.<br />

There are three other important things to remember about placeholders:<br />

• Placeholders must be unique within a query, and must begin with a colon.<br />

• Placeholders should never have quotation marks around them, regardless of<br />

the data type. The database server will handle that for us.<br />

• Placeholders should be used for all literal data, even if it will not vary.<br />

This third point is important for cross-database portability, as separating out literal<br />

values allows database drivers to make database-specific optimizations.<br />

[ 364 ]

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

Saved successfully!

Ooh no, something went wrong!