bobbyjones bobbyjones - 20 days ago 13
PHP Question

how to properly use while loop in PDO fetchAll

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;
}


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


Now, since
(PDO::FETCH_ASSOC)
is already declared in my function.

how would i properly create my
while
loop to print the values in 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..

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.

$sql = getContent();

while ($row = $sql->fetchAll(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$content = $row['content'];
}

Answer
function getContent() {
    $db = PDOconn();
    $query = "SELECT * FROM posts ORDER BY id DESC LIMIT 0,3";
    $sql = $db->prepare($query);
    $sql->execute();
    $rows = $sql->fetchAll();
    return $rows;
}

$data = getContent();
foreach($data as $row) {
    $id = $row['id'];
    $content = $row['content'];
}
Comments