0

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.

1
  • I solved it already, I was missing ->fetchAll(). dd() is just a helper function, <pre> print_r($obj) </pre> Commented Jul 21, 2014 at 15:47

1 Answer 1

4

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

?>
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I can't believe I forgot to add ->fetchAll(). Without it still loops one time. Thanks and sorry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.