How to run a Drupal 7 query outside of Drupal

Drupal query FAQ: How can I run a Drupal query outside of Drupal, i.e., from the command line? (Drupal 6 or Drupal 7)

Last night I was reading the excellent book Pro Drupal 7, and I stumbled on most of the solution for running a Drupal query from the command line. The book was exactly correct, except for one missing step, which may have been something that changed after publication.

Run a Drupal query from the command line

There's no better way to share this solution for how to run a Drupal query outside of Drupal than to show the code, so here's some PHP source code that shows how this works:

<?php

$drupal_root_dir = '/home/al/html';

# make your drupal directory php's current directory
chdir($drupal_root_dir);

# not shown in the book, i had to set this constant
define('DRUPAL_ROOT', $drupal_root_dir);

# bootstrap drupal up to the point the database is loaded
include_once('./includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

# run whatever query you want ...
$result = db_query('SELECT title FROM {node}');

# do something with the result ...
print_r($result);

?>

As I shared in the source code comments, I had to set the DRUPAL_ROOT constant for this code to work; the rest of the code comes almost directly from the Pro Drupal 7 book.

The book also didn't mention that you might get the dreaded PHP MySQL can't connect to socket error. Of course I ran into that error, and described the solution in my PHP PDOException SQLSTATE MySQL can't connect socket error article.

Also, I just tested this with Drupal 7, but haven't tried this with Drupal 6 yet, but if it doesn't work out of the box with Drupal 6, it may work with a little modification. (I don't think the db_query function was available in Drupal 6, though I could be wrong.)

Drupal command line query - Summary

I hope this brief look at how to run a Drupal query from the command line has been helpful. Of course most of the credit goes to the Pro Drupal 7 authors, so here's a link to Pro Drupal 7 at Amazon .