Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have this query

$categories = $dbh->query(" SELECT * FROM categories ORDER BY name ASC ");

and I need to loop two times over this array.

foreach($categories as $category) {
    dd($category);
}
echo '---------------';
foreach($categories as $category) {
    dd($category);
}

This code returns

stdClass Object
(
    [id] => 24
    [name] => granchi
    [slug] => granchi
)
stdClass Object
(
    [id] => 26
    [name] => molluschi
    [slug] => molluschi
)
stdClass Object
(
    [id] => 25
    [name] => pesci
    [slug] => pesci
)
---------------

In the second loop the array becomes empty. I have found a similar question, Two While Loops, Second Returns Empty Array? , but I didn't find a similar solution for PDO.

Without querying two times creating two identical arrays, how do I loop through them twice ?

And I do not understand why it empties after the first loop.

share|improve this question
    
What does dd() do? –  Mr. Llama Jul 21 '14 at 14:23
    
I solved it already, I was missing ->fetchAll(). dd() is just a helper function, <pre> print_r($obj) </pre> –  C. Ovidiu Jul 21 '14 at 15:47

1 Answer 1

up vote 4 down vote accepted

You must first fetch the result of a query into an array.

Mysqli:

<?php

$db = new mysqli('localhost', 'root', '', 'test');

if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

$sql = " SELECT * FROM categories ORDER BY name ASC ";

if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}

while($row = $result->fetch_assoc()){
    echo $row['**column name**'] . '<br />';
}

?>

PDO:

<?php

$db = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '');

$sql = "SELECT * FROM categories ORDER BY name ASC ";

try {
    $stmt = $db->query($sql);
} catch(PDOException $ex) {
    echo "An Error occured!";
}

$result = $stmt->fetch(PDO::FETCH_ASSOC);

foreach($result as $key => $val)
    {
    echo $key.' - '.$val.'<br />';
    }

?>
share|improve this answer
    
Oh, I can't believe I forgot to add ->fetchAll(). Without it still loops one time. Thanks and sorry –  C. Ovidiu Jul 21 '14 at 14:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.