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();
?>

db_query($query):在当前数据库执行标准查询操作。$query应该是一条正确的sql语句,注意事项有:
1.用正确的占位符取代sql语句中的值: %s, %d, %f, %b (二进制数据请不要直接放在 ''里) 和%%.%s可代替字符串,%d可表示双精度数字,%f为单精度数字,%b为二进制字节流。
2.在sql里把表放在{}里,以免混淆。比如,

sql = 'SELECT * FROM {node} n WHERE n.nid = %d';
db_rewrite_sql():
db_fetch_object():
db_fetch_array($result):将一条查询结果作为数组返回。
db_result():
pager_query():
limei 答复于
wrp的头像

$nids = array(5, 3, 1, 4, 2);
$sql = "SELECT
          nid, title, FIELD(nid, :nids) sortkey
          FROM
            {node}
          WHERE
            nid IN (:nids)
            AND type = :type
            AND status = 1
          ORDER BY sortkey";

$result_nid = db_query($sql, array(':nids' => $nids, ':type' => 'article'))
                ->fetchAll();
wrp 答复于