WebTechKitchen; Your Web Technology Kitchen, contact us to create, or maintain your websites and other digital properties.

db_query in drupal .... creating sql queries the drupal way (Drupal 6)

Submitted by barnettech on Mon, 12/14/2009 - 10:23

good drupal.org documentation is here: http://drupal.org/node/101496 getting a single value: use db_result

$result=db_result(db_query('Select uid from {users} where uid = %d',5));

getting multiple rows: use db_query

$result = db_query('SELECT a, b, c FROM d WHERE x > 300');
while ($row = db_fetch_array($result)) {
  $output .= 'a = ' . $row['a'] . ', b = ' . $row['b'] . ' , and c = ' . $row['c'] . '
';
}

getting a limited range of results: use db_query_range start and stop values of 0 and 10 below for the range:

$result = db_query_range(db_rewrite_sql($sql), $type, $status, 0, 10);

See Pro Drupal Development Book (for Drupal 6) page 94 for detailed examples.


db_query(' SELECT * FROM {table_name} WHERE vid = %d' , $node- >vid);

%s String %d Integer %f Float %b Binary data; do not enclose in ' ' %% Inserts a literal % sign (e.g., SELECT * FROM {users} WHERE name LIKE ' %%%s%%' ) And if the values are in an array that you are retrieving. You'll receive just this useless message if you don't use db_fetch array: Resource id #82 where 82 will change depending on the query.


$check_event_id = db_fetch_array(db_query('SELECT field_id_value from {content_type_event_calendar} where field_id_value = %d', $event->id));
print 'check_event_id is '.$check_event_id['field_id_value'];