My table ('contas
') has columns that correspond to years (2014, 2015, etc...
) among other columns, like:
id | name | notes | 2014 | 2015 | 2016
1 | abc | whatever| 5.25 | 8.50 | 9.50
I want to use PHP to select the column that corresponds to the current year from that table.
I have:
$ano=date('Y');
$ano=(string)$ano;
$sql = "SELECT `id`, `name`, `notes`, $ano AS 'saldo' FROM `contas` WHERE ...";
$result = $pdo->query($sql);
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
In the column 'saldo
' I'm getting 2014
for every row, instead of the values of the table.
I tried inserting $ano
into single and double quotes in the query, but it didn't work.
Escape the column name..
$sql = "SELECT `id`, `name`, `notes`, `$ano` AS 'saldo' FROM `contas` WHERE ...";
You could try this:
$ano=date('Y');
$sql = "SELECT `id`, `name`, `notes`,`".$ano."` AS 'saldo' FROM `contas` WHERE ...";