绑定结果集中的列到PHP变量是一种使每行包含的数据在应用程序中立即可用的有效方法。下面的例子演示了 PDO 怎样用多种选项和缺省值绑定和检索列。
<?php
function readData($dbh) {
$sql = 'SELECT name, colour, calories FROM fruit';
try {
$stmt = $dbh->prepare($sql);
$stmt->execute();
/* 通过列号绑定 */
$stmt->bindColumn(1, $name);
$stmt->bindColumn(2, $colour);
/* 通过列名绑定 */
$stmt->bindColumn('calories', $cals);
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
$data = $name . "\t" . $colour . "\t" . $cals . "\n";
print $data;
}
}
catch (PDOException $e) {
print $e->getMessage();
}
}
readData($dbh);
?>
apple red 150
banana yellow 175
kiwi green 75
orange orange 150
mango red 200
strawberry red 25