I have a PHP variable $col
with a column name. I want to create a query with PDO, that selects the value of that column. I know how to use bindValue()
, and tried the following:
$db = new PDO('mysql:host='. $db_host . ';dbname=' . $db_name . ';charset=utf8', $db_user, $db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function get_user($id, $column){
$sql = "
SELECT :col
FROM users
WHERE `id` = :id;";
try {
$st = $db->prepare($sql);
$st->bindValue('col', $column, PDO::PARAM_STR);
$st->bindValue(':id', $id, PDO::PARAM_INT);
$st->execute();
$result = $st->fetch();
return $result;
} catch (PDOException $e) {
echo "Database query exception: " . $e->getMessage();
return false;
}
}
That results in the following exception: Database query exception: SQLSTATE[42S22]: Column not found: 1054 Unknown column ''name'' in 'field list'
for $col = 'name'
. Of course, the column name
does exist.
It works well on WHERE = :value
, but I can not get it working for a column. How to achieve this?
Addition: I did found the function bindColumn()
, but I think that does the opposite, binding the column name to a PHP variable instead of binding a variable to the column.