PDO 使用execute方法获取执行结果
(2014-10-19 19:01:31)
					
											标签:
																				
                            it | 
					分类: PHP | 
fetchAll()
array PDOStatement::fetchAll ()
返回一个数组,包含结果集中的所有行(rows)。每一行为一个有列的值的数组,或一个对象,每个属性对应一个列值。没有返回数据时,为一个空数组,异常返回false。
示例:
< ?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
? >
输出结果:
Array
(
)
fetch(), fetchObject()方法
mixed PDOStatement::fetch()
从结果集中以数组形式返回一行,数组关联索引为列名,或数值索引。
fetchObject()方法以对象形式返回一行,对象属性名为列名。
示例:
< ?php
function readDataForwards($dbh) {
}
function readDataBackwards($dbh) {
}
print "Reading forwards:\n";
readDataForwards($conn);
print "Reading backwards:\n";
readDataBackwards($conn);
? >
closeCursor()方法
bool PDOStatement::closeCursor (void)
释放到服务器的连接,已使其他SQL语句可以执行,但同时保留语句状态,可以再次执行。
示例:
< ?php
//Create a PDOStatement object
$stmt = $dbh->prepare('SELECT foo FROM bar');
//Create a second PDOStatement object
$otherStmt = $dbh->prepare('SELECT foobaz FROM foobar');
//Execute the first statement
$stmt->execute();
// Fetch only the first row from the results
$stmt->fetch();
// The following call to closeCursor() may be required by some drivers
$stmt->closeCursor();
// Now we can execute the second statement
$otherStmt->execute();
? >
结果集行、列计数
int PDOStatement::columnCount(void)
int PDOStatement::rowCount (void)
示例一:
< ?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
//Count the number of columns in the (non-existent) result set
$colcount = $sth->columnCount();
print("Before execute(), result set has $colcount columns (should be 0)\n");
$sth->execute();
//Count the number of columns in the result set
$colcount = $sth->columnCount();
print("After execute(), result set has $colcount columns (should be 2)\n");
? >
示例二:
< ?php
// Delete all rows from the FRUIT table
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();
// Return number of rows that were deleted
print("Return number of rows that were deleted:\n");
$count = $del->rowCount();
print("Deleted $count rows.\n");
? >
示例三:
< ?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {

加载中…