0

This does not work:

$stmt = $pdo->prepare("SELECT * FROM location ORDER BY ? ASC");
$orderValue = "location_name";
$stmt->execute([$orderValue]);

How can I ortder the result by location_name?

Rawland Hustle
  • 781
  • 1
  • 10
  • 16
  • 1
    You can't generally (i.e. this isn't always true depending on things like emulate_prepares) use placeholders for identifiers (column names for example). Depending on where the identifier string comes from (location_name in this case), you can put the name directly in the query. – Jonnix Jul 22 '19 at 10:38
  • Thanks! The value to order by is hard coded by me. It should be safe to put it in the query then, right? – Rawland Hustle Jul 22 '19 at 10:43
  • 1
    Yes, that sounds fine in this case. – Jonnix Jul 22 '19 at 10:44
  • @Jonnix it is *always* true – Your Common Sense Jul 22 '19 at 11:41
  • @YourCommonSense I'll happily take your word for it. There was just something niggling in the back of my mind about placeholders and emulation working differently. – Jonnix Jul 22 '19 at 11:48
  • Different people understand the term "hardcode" differently, so make sure the field name is [indeed chosen from values *explicitly* written in your *PHP* code](https://phpdelusions.net/pdo_examples/order_by). – Your Common Sense Jul 22 '19 at 12:08

0 Answers0