How do I set ORDER BY params using prepated PDO statement?

Posted by Marlorn on Stack Overflow See other posts from Stack Overflow or by Marlorn
Published on 2010-03-30T02:01:19Z Indexed on 2010/03/30 2:03 UTC
Read the original article Hit count: 357

Filed under:
|
|

I'm having problems using params in the ORDER BY section of my SQL. It doesn't issue any warnings, but prints out nothing.

$order = 'columnName';
$direction = 'ASC';

$stmt = $db->prepare("SELECT field from table WHERE column = :my_param ORDER BY :order :direction");
$stmt->bindParam(':my_param', $is_live, PDO::PARAM_STR);
$stmt->bindParam(':order', $order, PDO::PARAM_STR);
$stmt->bindParam(':direction', $direction, PDO::PARAM_STR);
$stmt->execute();

The :my_param works, but not :order or :direction. Is it not being internally escaped correctly? Am I stuck inserting it directly in the SQL? Like so:

$order = 'columnName';
$direction = 'ASC';

$stmt = $db->prepare("SELECT * from table WHERE is_live = :is_live ORDER BY $order $direction");

Is there a PDO::PARAM_COLUMN_NAME constant or some equivalent?

Thanks!

© Stack Overflow or respective owner

Related posts about php

Related posts about pdo