Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to properly use while loop in PDO fetchAll

Tags:

php

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

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'];
}
like image 551
bobbyjones Avatar asked Oct 21 '13 07:10

bobbyjones


People also ask

What does PDO fetchAll return?

Return Values ¶ PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name. An empty array is returned if there are zero results to fetch.

What is the difference between fetch and fetchAll?

fetchall() fetches all the rows of a query result. An empty list is returned if there is no record to fetch the cursor. fetchone() method returns one row or a single record at a time. It will return None if no more rows / records are available.

Which one is default mode of fetching data in PDO?

PDO::FETCH_BOTH (default) Returns an array indexed by both column name and 0-indexed column number as returned in your result set.


1 Answers

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']; } 
like image 156
Hanky Panky Avatar answered Sep 23 '22 18:09

Hanky Panky