如何在PDO fetchAll中正确使用while循环 [英] how to properly use while loop in PDO fetchAll
问题描述
请放心,我才刚刚开始学习PDO,仍然在寻找将mysqli转换为PDO的方法.
please be easy on me, i just started learning PDO and still finding my way how to convert my mysqli to 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;
}
通常,当我在mysqli中返回$row
时,我会在while循环中定义fetch_assoc()
.
normally when i return $row
in mysqli, i would define fetch_assoc()
in my while loop.
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$content = $row['content'];
}
现在,因为在我的函数中已经声明了(PDO::FETCH_ASSOC)
.
Now, since (PDO::FETCH_ASSOC)
is already declared in my function.
我将如何正确创建我的while
循环以在PDO中打印值?
how would i properly create my while
loop to print the values in PDO?
更新的代码
[edit] updated code
我将在函数外部声明我的while
循环.所以我需要一些可以从我的函数中返回的东西,但是我不知道那是什么.
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..
function getContent() {
$db = PDOconn();
$query = "SELECT * FROM posts ORDER BY id DESC LIMIT 0,3";
$sql = $db->prepare($query);
$row = $sql->execute();
return $row;
}
这是我在函数外的while循环.
this is my while loop outside the function.
$sql = getContent();
while ($row = $sql->fetchAll(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$content = $row['content'];
}
推荐答案
使用fetchAll()
,您完全不必使用while
.当此函数返回一个 array 时,您必须使用foreach()
代替:
With fetchAll()
you don't have to use while
at all. As this function returns an array, you have to use foreach()
instead:
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'];
}
这篇关于如何在PDO fetchAll中正确使用while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!