SQL ORDER BY using prepared statements

前端 未结 2 1120
攒了一身酷
攒了一身酷 2021-01-07 15:45

I\'ve tried all different kinds of variations of this code and can\'t get it to work, can anyone point me in the right direction?

if(isset($_GET[\'s\']) And          


        
相关标签:
2条回答
  • 2021-01-07 16:22

    Only data can be bound with placeholders,column or table names cannot be bound.

    0 讨论(0)
  • 2021-01-07 16:23

    Look at these links:

    Mysqli Prepare Statements + Binding Order BY

    As the php.net link you found states, you cannot use bind variables for identifiers. You'll need a workaround. mysql_real_escape_char would certainly be one way.

    ... and ...

    How do I use pdo's prepared statement for order by and limit clauses?

    For this reason the ORDER BY fields should form part of the SQL string passed into the prepare() method, rather than being bound to the query prior to execute().

    ==========================================================

    ADDENDUM:

    Since you're already effectively validating the column names and "ASC/DESC" clause before your "prepare", there's no danger of SQL Injection.

    I'd just build the string:

    $sql = 
      "SELECT * FROM messages WHERE " .
      "receiver = :id AND rhide = 0 " .
      "ORDER BY " . $sortingby . " " . $orderingby;
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->execute();
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    0 讨论(0)
提交回复
热议问题