Selecting columns from resultset into array
I'm trying to get a number of columns from a PDO resultset into seperate arrays, so resulting as such:
<?php
$query = 'SELECT col1,col2 FROM tbl_imaginary';
...
$col1 = array(col1_row1, col1_row2,...);
$col2 = array(col2_row1, col2_row2,...);
?>
I know I could loop through the resultset with fetch, but it seems more efficient to use fetchAll(PDO:FETCH_COLUMN). However, once you do this, you can't perform it again unless you perform execute() on the statement handle again. I get why, you can't empty the cookie jar and then do the same again unless you fill it up again - kind of thing. So I thought I would copy the statement handle object and fetch columns of it as such:
<?php
$sh->execute();
for ($i=0; $i<$sh->columnCount(); $i++)
{
$tmp_sh = $sh;
$output[$i] = $tmp_sh->fetchAll(PDO::FETCH_COLUMN);
}
?>
开发者_开发技巧
However, this, just like doing fetchAll() on the original statement handle itself, outputs only the first column and not the second.
If anyone would be so kind to explain this behaviour to me and / or suggest a solution I would be most grateful.
Thank you very much in advance for your time.
Edit: So basically I want to get 2 (or more) columns from one resultset as seperate arrays, just like you would if you would perform 2 (or more) individual queries on 1 single column. The above is mostly an explanation of how I've tried to do this so far.
Why do you need two separate arrays?
$statement = $db->prepare('SELECT col1, col2 FROM tbl_imaginary');
$statement->execute();
foreach($sth->fetchAll() as $row) {
echo $row['col1'], $row['col2'];
}
精彩评论