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 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题