問題描述
請(qǐng)放輕松,我剛開始學(xué)習(xí) PDO 并且仍在尋找如何將我的 mysqli 轉(zhuǎn)換為 PDO 的方法.
please be easy on me, i just started learning PDO and still finding my way how to convert my mysqli to PDO.
所以我有一個(gè)函數(shù)可以從我的數(shù)據(jù)庫中獲取內(nèi)容
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;
}
通常當(dāng)我在mysqli中返回$row
時(shí),我會(huì)在while循環(huán)中定義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'];
}
現(xiàn)在,因?yàn)?(PDO::FETCH_ASSOC)
已經(jīng)在我的函數(shù)中聲明了.
Now, since (PDO::FETCH_ASSOC)
is already declared in my function.
我將如何正確創(chuàng)建我的 while
循環(huán)來打印 PDO 中的值?
how would i properly create my while
loop to print the values in PDO?
更新代碼
我將在函數(shù)之外聲明我的 while
循環(huán).所以我需要一些東西從我的函數(shù)中返回,但我不知道那是什么..
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;
}
這是我在函數(shù)外的while循環(huán).
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
根本.由于此函數(shù)返回一個(gè)數(shù)組,您必須改用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'];
}
這篇關(guān)于如何在 PDO fetchAll 中正確使用 while 循環(huán)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!