user2887749
user2887749

Reputation: 79

PDO making a while loop function

Yeah I'm unsure how to even ask this question.

Let me just try to make an example of what I want to do here.

function getRecents()
{
    global $sql;
    $buffer = $sql->prepare("SELECT * FROM `foo` WHERE `exposure` = 'public' ORDER BY `id` DESC LIMIT 5");
    $buffer->execute();
    return $buffer->fetch(PDO::FETCH_OBJ);
}

while($pd = getRecents())
{
 echo $pd->id;
}

Just as if I was going to do this below. Obviously because I use recents more than once I'm not going to throw this all over the place.

    $buffer = $sql->prepare("SELECT * FROM `foo` WHERE `exposure` = 'public' ORDER BY `id` DESC LIMIT 5");
    $buffer->execute();
    while($foo = $buffer->fetch(PDO::FETCH_OBJ))
    echo $foo->id;

I think someone will understand what I'm trying to do, if so please I'm so confused. I would google it but not even sure how to.

Upvotes: 0

Views: 112

Answers (2)

speccode
speccode

Reputation: 1562

I guess you should try something like this:

function getRecents()
{
    global $sql;
    $buffer = $sql->prepare('SELECT * FROM foo WHERE exposure = "public" ORDER BY id DESC LIMIT 5');
    $buffer->execute();
    return $buffer->fetchAll(PDO::FETCH_OBJ);
}

$recents = getRecents();

foreach ($recents as $item) {
    echo $item->id;
}

Upvotes: 1

Xeoncross
Xeoncross

Reputation: 57184

A foreach loop would be better if there is a set array of objects/arrays.

$buffer = $sql->prepare('SELECT * FROM foo WHERE exposure = "public" ORDER BY id DESC LIMIT 5');
$buffer->execute();
foreach($buffer->fetchAll(PDO::FETCH_OBJ) as $row) {
    print_r($row);
}

Upvotes: 0

Related Questions