php 如何在 PDO fetchAll 中正确使用 while 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19488364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to properly use while loop in PDO fetchAll
提问by bobbyjones
please be easy on me, i just started learning PDO and still finding my way how to convert my mysqli to PDO.
请对我放轻松,我刚开始学习 PDO 并且仍在寻找如何将我的 mysqli 转换为 PDO 的方法。
so i have a function to get the contents from my database
所以我有一个函数可以从我的数据库中获取内容
function getContent() {
$db = PDOconn();
$query = "SELECT * FROM posts ORDER BY id DESC LIMIT 0,3";
$sql = $db->prepare($sql);
$row = $sql->fetchAll(PDO::FETCH_ASSOC);
return $row;
}
normally when i return $row
in mysqli, i would define fetch_assoc()
in my while loop.
通常当我$row
在 mysqli 中返回时,我会fetch_assoc()
在我的 while 循环中定义。
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$content = $row['content'];
}
Now, since (PDO::FETCH_ASSOC)
is already declared in my function.
现在,因为(PDO::FETCH_ASSOC)
已经在我的函数中声明了。
how would i properly create my while
loop to print the values in PDO?
我将如何正确创建while
循环以打印 PDO 中的值?
[edit] updated code
[编辑] 更新代码
i will be declaring my while
loop outside of the function. so i need something to return from my function but i dont know what that is..
我将while
在函数之外声明我的循环。所以我需要一些东西从我的函数中返回,但我不知道那是什么..
function getContent() {
$db = PDOconn();
$query = "SELECT * FROM posts ORDER BY id DESC LIMIT 0,3";
$sql = $db->prepare($query);
$row = $sql->execute();
return $row;
}
this is my while loop outside the function.
这是我在函数外的 while 循环。
$sql = getContent();
while ($row = $sql->fetchAll(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$content = $row['content'];
}
回答by Hanky Panky
With fetchAll()
you don't have to use while
at all. As this function returns an array, you have to use foreach()
instead:
有了fetchAll()
你根本不必使用while
。由于此函数返回一个数组,因此您必须foreach()
改用:
function getContent() {
$db = PDOconn();
$query = "SELECT * FROM posts ORDER BY id DESC LIMIT 0,3";
$sql = $db->prepare($query);
$sql->execute();
return $sql->fetchAll();
}
$data = getContent();
foreach($data as $row) {
$id = $row['id'];
$content = $row['content'];
}