Drupal 7 basic db_querys
Examples
How to do Database Queries with db_query and db_select.
SUMMARY
1. Setup
2. db_query
3. db_select
1. Setup
- Create an article node/add/article- Create a template for it (node--[nid].tpl.php)
- Create dummy content with Devel (Generate users/generate content).
2. db_query
Basic fetch
To fetch all node titles you would normally do this kind of sql statementIn Drupal you do it like this with db_query() :
So pretty much the same expect curly brackets are used around the table { table } .
These add table prefix to your tables so that you can share your database across multiple sites.
Limit results
You can limit results like this in sql :In Drupal you would do this:
In Drupal LIMIT is abstracted in db_query_range() because of syntax differences between different databases (like in MSSQL you have to write TOP(2) to get top two rows but in MySQL you would use LIMIT 2)
Variables
In sql you use variables like this:In Drupal you use placeholders like this:
Placeholders are used to add a security layer that inserts variables in a secure manner so you don't have to escape or quote them before they are added into the query.
Printing the values
I used foreach to iterate through the result set.You could also get an array with this:
You can iterate through that exactly the same way:
If you need just one item, you can use fetchField();
3. db_select
You can also use more flexible but slower db_select() to fetch items.Here is how to do same thing with db_select: