douchi5822 2015-10-08 08:07
浏览 57
已采纳

使用PDO准备和绑定语句的条件查询

I am converting all my queries from mysql to PDO, and in this process I found a conditional query like a follows

if (isset($parameters['searchTerm'])) {
    $where =" And title LIKE '%{$parameters['searchTerm'] }%'";
} 

$sql = "Select * from table data Where tableId = 5 {$where} ";

and when I am trying to convert this query in PDO the expected syntax is as follows

if (isset($parameters['searchTerm'])) {
    $where =" And title LIKE :searchTerm";
} 



$sql = $dbh->prepare("Select * from table data Where tableId = 5 {$where}");



if (isset($parameters['searchTerm'])) {
    $sql ->bindParam(':searchTerm', '%{$parameters['searchTerm'] }%');
} 

$sql ->execute();

Now as you can See that the if condition if (isset ($parameters ['searchTerm'] )) {...} is repeated twice.

The reason is

  1. I can not prepare the sql query before $where is being set thus $sql variable is initialized after first if statement
  2. I can not bind the parameters until I prepare the sql so it has to be placed after the $sql is being prepared

So there is one if statement before $sql = $dbh->prepare("Select * from table data Where tableId = 5 {$where}"); and one if statement after.

And my question is: Is there a way to remove this redundant if statement or I have to do it this way only.

  • 写回答

1条回答 默认 最新

  • dsfdf854456 2015-10-08 08:12
    关注

    you can use handy PDO's feature that lets you to send array with parameters straight into execute()

    $where  = '';
    $params = array();
    if (isset($parameters['searchTerm'])) {
        $where =" And title LIKE :searchTerm";
        $params['searchTerm'] = "%$parameters[searchTerm]%";
    }
    $sql = "Select * from table data Where tableId = 5 $where";
    $pdo->prepare($sql)->execute($params);
    

    Note that PHP syntax in your code is also wrong.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?