使用$stmt->fetch(PDO::FETCH_ASSOC)
时如何正确输出数据?现在我在做
"select name, author, title from d_books"
// Other PDO stuff goes here
$arr = $stmt->fetch(PDO::FETCH_ASSOC);
foreach ($arr as $titleData) {
echo $titleData['name'];
}
答案 0 :(得分:11)
$pdo = new PDO(/*Your credentials*/);
$sql = `select name, author, title from d_books`
$stmt = $pdo->prepare($sql);
$stmt->execute();
while ($arr = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $arr['name'];
}
或
$pdo = new PDO(/*Your credentials*/);
$sql = `select name, author, title from d_books`
$stmt = $pdo->prepare($sql);
$stmt->execute();
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($arr as $titleData) {
echo $titleData['name'];
}
在运行不带任何参数的查询时,您总是可以使用pdo->query()
方法,这样更快,但我不相信这种情况发生得太多(运行没有任何参数的查询)。