How to apply bindValue method in LIMIT clause?

后端 未结 10 2381
旧巷少年郎
旧巷少年郎 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: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.

提交回复
热议问题