Drupal7 db_query SQL查询运用

本文介绍了在PHP中如何高效地进行数据库查询操作,包括使用fetchField()获取单个记录的方法,以及如何通过fetchObject(), fetchAssoc()等函数处理查询结果。此外,还提供了多种数据检索方式,如fetchAll(), fetchAllAssoc()等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

你可以使用 fetchField() 来获得单个记录. 例如:

<?php
$node_title = db_query('SELECT title FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
?>

//查询

<?php

$uid = 1;
$result = db_query(‘SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid’, array(‘:uid’ => $uid));
// 返回的结果是一个对象

//通过一个foreach来进行输出

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
}

或者是(推荐方法)

while($record = $result->fetchassoc()){

    //写你想要的

    //那么输出的就是一个数组

}

//对象,数组,值

<?php
// 用这个查询来举例
$uid = 1;
$result = db_query(‘SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid’, array(‘:uid’ => $uid)); 

// 对象
$record = $result->fetchObject();

// 数组
$record = $result->fetchAssoc();

// 只输出第一条数据
$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();
?>

 

转载于:https://my.oschina.net/kenblog/blog/191477

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值