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

后端 未结 8 2101
心在旅途
心在旅途 2020-11-22 15:37

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 = \'column         


        
相关标签:
8条回答
  • 2020-11-22 16:12

    Unfortunely I guess you could not make it with prepared statements. It would make it no cacheable since different columns may have values that could be sorted with special sorting strategies.

    Create query by using standard escapes and execute it directly.

    0 讨论(0)
  • 2020-11-22 16:14

    Yes, you're stuck inserting it directly in the SQL. With some precautions, of course. Every operator/identifier must be hardcoded in your script, like this:

    $orders=array("name","price","qty");
    $key=array_search($_GET['sort'],$orders);
    $order=$orders[$key];
    $query="SELECT * from table WHERE is_live = :is_live ORDER BY $order";
    

    Same for the direction.

    I wrote a whitelisting helper function to be used in such cases, it greatly reduces the amount of code that needs to be written:

    $order = white_list($order, ["name","price","qty"], "Invalid field name");
    $direction = white_list($direction, ["ASC","DESC"], "Invalid ORDER BY direction");
    
    $sql = "SELECT field from table WHERE column = ? ORDER BY $order $direction";
    $stmt = $db->prepare($sql);
    $stmt->execute([$is_live]);
    

    The idea here is to check the value and raise an error in case it is not correct.

    0 讨论(0)
提交回复
热议问题