Lelio Faieta Lelio Faieta - 8 days ago 6
PHP Question

perform two different fetch on the same query result

I have this query:

$all = $dbh->query("SELECT DISTINCT movimenti.nome, SUM(movimenti_carta.importo)
FROM movimenti_carta JOIN movimenti ON movimenti_carta.movimento=movimenti.id
WHERE month(data)='$mese' AND year(data)='$anno' GROUP BY movimenti.nome");


It retrieves two columns from my db. What I want to do is to put each column in a separate array.
If I do:

$labels=$all->fetchAll(PDO::FETCH_COLUMN,0);


I get the values for the first column with the format I am looking for.
I tried to do:

$values=$all->fetchAll(PDO::FETCH_COLUMN,1);


after the first fetch but
$all
is unset by the first fetch and the result is that
$values
is an empty array (I was pretty sure of this but did give it a try).
I can build the arrays in php after I fetch an array with both columns but I was wondering how to get my goal using PDO api.

Answer

Of course it will never work this way, as fetchAll() returns data only once.

The only idea I could think of is PDO::FETCH_KEY_PAIR constant:

$data = $all->fetchAll(PDO::FETCH_KEY_PAIR);
$labels = array_keys($data);
$values = array_values($data);