bobbyjones
bobbyjones

Reputation: 2079

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

Upvotes: 23

Views: 67223

Answers (1)

Hanky Panky
Hanky Panky

Reputation: 46900

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

Upvotes: 38

Related Questions