Database access in Drupal


Drupal provides several functions to send queries to the database. The canonical form is db_query. Always use functions provided by Drupal to access the database to guard against SQL injections attacks.

<?php
/** Example 1 - Insecure
  * SQL injection via $type
  * Display node titles of type $type (input supplied by the user via a form textfield)
  */
$result = db_query("SELECT n.nid, n.title FROM {node} n WHERE n.type = '$type'");

$items = array();
while ($row = db_fetch_object($result)) {
  $items[] = l($row->title, "node/{$row->nid}");
}
return theme('item_list', $items);
?>


The most important usage is that if you want to access Drupal database from a script without loading anything else, you can include bootstrap.inc, and call drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE).
Below is what I got to work, from the directory drupal/modules/mymodule/script.php:

<?php
chdir('./../../'); // for relative path includes to work
include_once "includes/bootstrap.inc";

drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
$result = db_query("SELECT title FROM {node} n WHERE type = 'blog'");
while ($node = db_fetch_object($result)) {
   $str .= $node->title;
}
?>
 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s