duai3681 2014-08-26 21:26
浏览 51
已采纳

具有%和限制的PDO准备语句

I am really new to PDO, but I need to use it to avoid SQL injections.

Here is my SQL Query with the variables I've got via the POST Request and I want to do a PDO with that SQL Query (this version works):

if($refid == "") $refid="%";

$lastOrders = "SELECT * FROM Orders WHERE REFID LIKE'$refid' 
               ORDER BY dateAdded DESC LIMIT 0,$limiter";
$ps_orders = $db->query($lastOrders);
$data = $ps_orders->fetchAll();

My problem(s): The given $refid is either a number which I can find in the database, or it isn't specified by the POST Request (so the value is $refid="") and in that case I want to set the WHERE part to this: WHERE REFID LIKE '%', so I can see in that case all results for every "RefID". Is there a way to do it that way, or do I really need to create 2 different SQL Queries for both cases ?

My try (doesn't work can't figure out what the exactly problem is):

if($refid == "") $refid="%";

$sql = "SELECT * FROM Orders WHERE REFID LIKE :refid
        ORDER BY dateAdded DESC LIMIT :min,:max";
$ps_orders = $db->prepare($sql);
$ps_orders->bindParam(':refid', $refid, PDO::PARAM_STR);
$ps_orders->bindParam(':min', 0, PDO::PARAM_INT);
$ps_orders->bindParam(':max', (int)$limiter, PDO::PARAM_INT);
$ps_orders->execute();
$data = $ps_orders->fetchAll();
  • 写回答

1条回答 默认 最新

  • dongying6659 2014-08-26 21:34
    关注

    bindParam requires a variable reference so it won't work with as

    bindParam(":min", 0, PDO::PARAM_INT)
    

    You could create one like $zero = 0, but this seems unnecessary so you can just use bindValue instead. Same for (int)$limiter which becomes a value rather than a variable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题