Drupal 6: Database Select, Insert, Update and Delete Query with example

In Drupal system have its own query builder it will create a query on Drupal way and sent to the Database server. To run a Database query we have built our condition on a specific format. The function db_query() function helps us to achieve run database queries in Drupal 6. The below is the syntax and example using a different type of Database queries.



Note: The placeholder for numeric is %d and for string %s.

1. SELECT Query:
The SELECT query is used for retrieve records from Database. The below is the Syntax and example for SELECT query.


$result = db_query("SELECT * FROM {node} WHERE type = 'article' AND status = 1", 0, 10);
$output = array();
while ($data = db_fetch_object($result)) {
  $output[$data->title] = check_plain($data->title);

2. Insert Query:

The insert query is used for save Records in Database, the below example demonstrate about the Insert query.


db_query("INSERT INTO {node} (nid, title, created, uid, status) values(%d, '%s', '%s', %d, %d)", 0, 'First Node', time(), 1, 1);

If we have auto increment field than we pass the value as 0.

3. Update Query:
The UPDATE query is used for altering the existing content.


db_query("UPDATE {node} SET title = '%s', created = '%s', status = %d WHERE nid = %d", 'First Node Alter', time(), 0, 1);

4. Delete Query:
The DELETE query is used for remove files from Database.


db_query("DELETE FROM {node} WHERE nid = %d", 1);