PDO - how to fetch 2 sets of results from the same execute()

So I have the following PDO calls that work great:


$stmt = $dbh->conn->prepare($sql);
$stmt->execute();
$list_data = $stmt->fetchAll();

Then I realized I also need the db id’s from the same query in a flat array. Ideally I would then call this code:


$flat_array = $stmt->fetchAll(PDO::FETCH_COLUMN, 0); // db id is the first column

But this doesn’t work.

Is it possible to fetch data twice after executing a sql statement 1 time?

Thanks for looking.

If the only difference in the query is the ID field, could you add that to the list of fields in the SELECT clause?

The id is currently there. I needed the id’s in a flat array, and the first fetchall() returns a multidimensional. Ultimately I was trying to avoid executing the query a second time just to run: $flat_array = $stmt->fetchAll(PDO::FETCH_COLUMN, 0); – which does return flat arrays, or looping the same record set a second time to get the desired array format. Not a prefect solution, but I was able to build an array i needed from the 1 and only time the orignial record set is looped.

Hi sessions,can you please show to us how you did the sql statement?

Once you’ve fetched the results from a PDOStatament you can’t fetch them again, as you’ve found out.

If you’re on PHP >= 5.5 you can use array_column


$ids = array_column($result, 'id');

There is a package on packagist for PHP < 5.5: https://packagist.org/packages/rhumsaa/array_column

Very useful function, good to have!