We help IT Professionals succeed at work.

EASY: Module that reads data from a custom table

I am a drupal beginner (read and completed the first two tutorials on module development), and would like to know more about DB access.

Let's say, for sake of example, that I want to create a module that sorts recipes according to page and recipe number; to this extent I create, inside the drupal DB, a table called "recipes".

Can I query this table directly with drupal functions? And if yes, how? Does it has to follow the table naming conventions of the other tables (prefix, ecc.)?

I would greatly appreciate if someone could write a sample meta-code on how to get, say, recipe_text and recipe_difficulty fields from a fictional "recipes" table.
Comment
Watch Question

Commented:
Check out the database example module here:
 http://drupal.org/project/examples

That's the easiest way to start

Author

Commented:
I'm sorry, but that's too much of a generic way to answer.
Commented:
OK,
I'm a bit of a newb myself when it comes to creating modules. The best help I've received in regards to building several different types of modules (and the answer I receive most of the time in my inquiries) is the "Examples for Developers" module:
http://drupal.org/project/examples

It gives you a start you can morph into other modules.

The "Examples for Developers" module is made up of several smaller modules. The one you need to look at and enable is the dbtng_example (description says "Database examples (DBTNG)").

Drupal 7 abstracts queries a bit for security and other reasons reasons (Drupal 6 was slightly more direct).

Taken straight from the code, querying a database would look something like this:
 *  // Old way
 *  $query = "SELECT * FROM {dbtng_example} n WHERE n.uid = %d AND name = '%s'";
 *  $result = db_query($query, $uid, $name);
 * @endcode

Open in new window


In Drupal 7, it works like this:
*   // SELECT * FROM {dbtng_example} WHERE uid = 0 AND name = 'John'
 *   db_query(
 *     "SELECT * FROM {dbtng_example} WHERE uid = :uid and name = :name",
 *     array(':uid' => 0, ':name' => 'John')
 *   )->execute();

Open in new window


Let me know if that helps better. Thanks for tolerating my briefness pre-coffee. ;)

Best regards,

Chris

Commented:
Edit: first example is Drupal 6, second example is Drupal 7

Author

Commented:
Thanks, will try that and will let you know.
D7 way:

// SELECT * FROM {dbtng_example} WHERE uid = 0 AND name = 'John'
      
            $query = db_select('dbtng_example', 'c');
            $return = $query
            ->fields('c', array('uid','name'))      
            //->condition('c.name', '%' . db_like('John') . '%', 'LIKE')      
            '->execute();

Author

Commented:
Worked a charm, thanks.