I am generating a table with this code:
if ($arch = $pdo->prepare("SELECT one, two, three, four FROM numbers)) {
$arch ->execute();
$data = $arch->fetchAll();
echo '<table>';
foreach ($data as $row){
echo '<tr>';
foreach ($row as $col){
$col=nl2br($col);
echo '<td>'.$col.'</td>';
}
echo '</tr>';
}
echo '</table>';
}
}
This populates a table with 4 columns.
How can I choose only 2 columns without changing the SELECT
query?
In other words, how can I choose the columns I want to populate the table? for example I would like to use only "three" and "four"...
I read about fetchAll(PDO::FETCH_COLUMN, 0)
but this seems to pick only one column. The same goes for fetchColumn()
. I want to pick more than one so I can populate my table with only the columns I need.
Alternatively, you can specify the columns you want as an array beforehand, and iterate over that array rather than the columns in the row.
$columns = array('I_like_this_column', 'this_one_too');
foreach ($columns as $colName)
echo '<td>' . nl2br($row[$colName]) . '</td>';
This has the added advantage of letting you specify the order the columns will appear in your output without changing your query.
And, as with @stUrb's answer, you need to turn on PDO::FETCH_ASSOC
for this to work.