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

后端 未结 8 2106
心在旅途
心在旅途 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:03

    It's possible use prepared statements in ORDER BY clause, unfortunately you need pass the order of column insted of the name and is required set PDO_PARAM_INT with type.

    In MySQL you can get the order of columns with this query:

    SELECT column_name, ordinal_position FROM information_schema.columns 
    WHERE table_name = 'table' and table_schema = 'database'
    

    PHP code:

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

提交回复
热议问题