drupal 6 和 drupal 7 db_query 用法

// Drupal 7
// Notice the place holders are now done using the same syntax as PDOs (:uid)
// Placeholders also don't need to be quoted anymore.
$uid = 1
;
$result = db_query(
'SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid'
, array(':uid' => $uid
));
// Result is returned as a iterable object that returns a stdClass object on each iteration
foreach ($result as $record
) {
 
// Perform operations on $record->title, etc. here.
  // in this example the available data would be mapped to object properties:
  // $record->nid, $record->title, $record->created
}

// Same example in Drupal 6
$uid = 1
;
$result = db_query(
"SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = %d"
, $uid
);
while (
$record = db_fetch_object($result
)) {
 
// Perform operations on $record->title, etc. here.
}
// NOTE: db_fetch_object and db_fetch_array have been removed from D7!

?>

 

// Using the same query from above...
$uid = 1
;
$result = db_query(
'SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid'
, array(':uid' => $uid
));

// Fetch next row as a stdClass object.
$record = $result->fetchObject
(); 

// Fetch next row as an associative array.
$record = $result->fetchAssoc
();

// Fetch data from specific column from next row
// Defaults to first column if not specified as argument
$data = $result->fetchColumn(1);
// Grabs the title from the next row

// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll
();

// Retrieve all records as stdObjects into an associative array
// keyed by the field in the result specified.
// (in this example, the title of the node)
$result->fetchAllAssoc('title'
);

// Retrieve a 2-column result set as an associative array of field 1 => field 2.
$result->fetchAllKeyed
();
// Also good to note that you can specify which two fields to use
// by specifying the column numbers for each field
$result->fetchAllKeyed(0,2);
// would be nid => created
$result->fetchAllKeyed(1,0);
// would be title => nid

// Retrieve a 1-column result set as one single array.
$result->fetchCol
();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($db_column_number
);

// Count the number of rows
$result->rowCount
();
?>

 

你可能感兴趣的:(用法,drupal,7,db_query)