How to apply bindValue method in LIMIT clause?

后端 未结 10 2420
旧巷少年郎
旧巷少年郎 2020-11-21 04:28

Here is a snapshot of my code:

$fetchPictures = $PDO->prepare(\"SELECT * 
    FROM pictures 
    WHERE album = :albumId 
    ORDER BY id ASC 
    LIMIT :s         


        
相关标签:
10条回答
  • 2020-11-21 05:28

    I remember having this problem before. Cast the value to an integer before passing it to the bind function. I think this solves it.

    $fetchPictures->bindValue(':skip', (int) trim($_GET['skip']), PDO::PARAM_INT);
    
    0 讨论(0)
  • 2020-11-21 05:29

    This just as summary.
    There are four options to parameterize LIMIT/OFFSET values:

    1. Disable PDO::ATTR_EMULATE_PREPARES as mentioned above.

      Which prevents values passed per ->execute([...]) to always show up as strings.

    2. Switch to manual ->bindValue(..., ..., PDO::PARAM_INT) parameter population.

      Which however is less convenient than an ->execute list[].

    3. Simply make an exception here and just interpolate plain integers when preparing the SQL query.

       $limit = intval($limit);
       $s = $pdo->prepare("SELECT * FROM tbl LIMIT {$limit}");
      

      The casting is important. More commonly you see ->prepare(sprintf("SELECT ... LIMIT %d", $num)) used for such purposes.

    4. If you're not using MySQL, but for example SQLite, or Postgres; you can also cast bound parameters directly in SQL.

       SELECT * FROM tbl LIMIT (1 * :limit)
      

      Again, MySQL/MariaDB don't support expressions in the LIMIT clause. Not yet.

    0 讨论(0)
  • 2020-11-21 05:30

    for LIMIT :init, :end

    You need to bind that way. if you had something like $req->execute(Array()); it wont work as it will cast PDO::PARAM_STR to all vars in the array and for the LIMIT you absolutely need an Integer. bindValue or BindParam as you want.

    $fetchPictures->bindValue(':albumId', (int)$_GET['albumid'], PDO::PARAM_INT);
    
    0 讨论(0)
  • 2020-11-21 05:30

    //BEFORE (Present error) $query = " .... LIMIT :p1, 30;"; ... $stmt->bindParam(':p1', $limiteInferior);

    //AFTER (Error corrected) $query = " .... LIMIT :p1, 30;"; ... $limiteInferior = (int)$limiteInferior; $stmt->bindParam(':p1', $limiteInferior, PDO::PARAM_INT);

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