問題描述
我無法從 fetchAll 獲取數據以進行選擇性打印.
I'm having trouble getting my data from fetchAll to print selectively.
在普通的 mysql 中,我是這樣做的:
In normal mysql I do it this way:
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)){
$id = $row['id'];
$n = $row['n'];
$k = $row['k'];
}
在 PDO 中,我遇到了麻煩.我綁定了參數,然后像上面一樣將獲取的數據保存到 $rs 中,目的是以相同的方式循環遍歷它..
In PDO, I'm having trouble. I bound the params, then I'm saving the fetched data into $rs like above, with the purpose of looping through it the same way..
$sth->execute();
$rs = $query->fetchAll();
現在是麻煩的部分.我該怎么做 PDO-wise 才能得到與上面的 while 循環匹配的東西?!我知道我可以使用 print_r() 或 dump_var,但這不是我想要的.我需要做我以前可以用常規 mysql 做的事情,比如根據需要單獨抓取 $id、$n、$k.可能嗎?
Now comes the trouble part. What do I do PDO-wise to get something matching the while loop above?! I know I can use print_r() or dump_var, but that's not what I want. I need to do what I used to be able to do with regular mysql, like grabbing $id, $n, $k individually as needed. Is it possible?
提前致謝..
推薦答案
應該是
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$n = $row['n'];
$k = $row['k'];
}
如果你堅持fetchAll
,那么
$results = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
$id = $row['id'];
$n = $row['n'];
$k = $row['k'];
}
PDO::FETCH_ASSOC
僅獲取列名并省略數字索引.
PDO::FETCH_ASSOC
fetches only column names and omits the numeric index.
這篇關于PDO 循環通過并打印 fetchAll的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!