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

后端 未结 8 2178
心在旅途
心在旅途 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 15:58

    I don't think you can get ASC/DESC as part of the prepared statement, but the column you can if you list them all in the sql query like so:

    // Validate between 2 possible values:
    $sortDir = isset($_GET['sortDir']) && $_GET['sortDir'] === 'ASC' ? 'ASC' : 'DESC';
    $sql = "
    ...
         order 
            by 
               case :orderByCol
                   when 'email' then email
                   when 'age' then age
                   else surname
               end
               $sortDir
    ";
    $stmt = $db->prepare($sql);
    $stmt->bindParam(':orderByCol', $someColumn);
    $stmt->execute();
    

    Since ASC/DESC is only two possible values, you can easily validate and select between them as hardcoded values using php code.

    You could also make use of the ELT(FIELD(,,,,,),,,,,) functions for this, but then ordering will always be done as a string, even if the column is a numeric data type that should be sorted using numeric semantics / collation.

提交回复
热议问题