使用$ stmt-> fetch(PDO :: FETCH_ASSOC)时如何输出数据;

时间:2013-10-14 15:45:40

标签: php mysql pdo

使用$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'];
}

1 个答案:

答案 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()方法,这样更快,但我不相信这种情况发生得太多(运行没有任何参数的查询)。