1

I have a Query like this in my PDO statement:

SELECT * FROM table WHERE ? = ? ORDER BY id DESC

I wanted to bind column name to first ? and the value to second ? (column = value)

I tried many things such as below, but they all fail or return empty array (when there should be result)

This returns empty array

$query = "SELECT * FROM table WHERE ? = ? ORDER BY id DESC"
$db->prepare($query);
$stmt->bindValue(1, $column, PDO::PARAM_STR);
$stmt->bindValue(2, $value, PDO::PARAM_STR);

and this one displays an error

$query = "SELECT * FROM table WHERE column = :value ORDER BY id DESC"
$db->prepare($query);
$stmt->bindColumn('column', $column);
$stmt->bindValue(':value', $value, PDO::PARAM_STR);

Column is variable, so i had to bind it and can't put it in query directly.

What am I doing wrong here? I tried many things but no luck...

Please note that I know how to bind values if column is static, my issue is when column is also variable like above.

Vladimir
  • 1,602
  • 2
  • 18
  • 40
  • @Andrew bindValue is fine... Why every one keep saying that? http://stackoverflow.com/questions/1179874/what-is-the-difference-between-bindparam-and-bindvalue – Vladimir Jun 05 '15 at 19:21
  • 1
    From the accepted answer _Table and Column names cannot be replaced by parameters in PDO._ – AbraCadaver Jun 05 '15 at 19:32
  • https://stackoverflow.com/questions/182287/can-php-pdo-statements-accept-the-table-or-column-name-as-parameter – Ashish Doneriya Mar 09 '18 at 11:41

1 Answers1

-2

It should be bindParam, but you can execute it with an array inside too that's the way I do it:

$query = $db->prepare( 'SELECT * FROM table WHERE column=\':value\' ORDER BY id DESC' );
$query->execute(array(
  ':value' => $value
));
N. Hamelink
  • 603
  • 5
  • 14