PDO MySQL预编译语句带有可选的where语句

时间:2016-09-15 22:26:57

标签: php mysql pdo prepared-statement

我正在处理从包含各种搜索选项的表单提交的查询,该搜索选项可能包含在查询中,也可能不包含在我的查询中。有没有更好的方法来动态地执行此操作,因为这似乎不起作用?

我一直收到错误Fatal error: Call to a member function fetchAll() on boolean。我知道这里有很多事情,我不想要大量的代码来阅读。所以简而言之,当我回显$ sql时,我的select语句看起来不错,但无论我做什么,我都会得到同样的错误,告诉我语句有问题。这种方法是否可行或我是否需要使用其他方法?如果是这样,什么是更好的方法?

 $sql = "SELECT DISTINCT mt.id, mt.name, mt.phone 
       FROM main_table mt
       LEFT JOIN jnct_tbl_srvstate st ON mt.id = st.mt_id
       LEFT JOIN jnct_tbl_equip eq on mt.id = eq.mt_id
       LEFT JOIN jnct_tbl_accessory ac ON mt.id = ac.mt_id
       LEFT JOIN tbl_car c ON mt.id = c.mt_id
       WHERE mt.id = c.id";

      if($state_array_count != 0){
         $sql.= " AND srvstate_id IN ($st_holders)";
      }    
      if($equip_array_count != 0){
         $sql.= " AND equip_id IN ($eq_holders)";  
      }
      if($accessory_array_count != 0){
         $sql.= " AND accessory_id IN ($ac_holders)";


      $sql.= " ORDER BY mt.id";

      $query = $db->prepare($sql);

合并上面的if语句是我真正需要帮助的。

 if($state_array_count != 0){     
     foreach($state_array as $st_placeholder => $st_value) {
        if($st_value != '') {
            $st_placeholder = ":$st_placeholder";
            $query->bindValue($st_placeholder, $st_value);
        }
     }
 }

 if($equip_array_count != 0){
      if($eq_value != '') {
          foreach($equip_array as $eq_placeholder => $eq_value) {
            $eq_placeholder = ":$eq_placeholder";
            $query->bindValue($eq_placeholder, $eq_value);
       }
    }
 }

 if($accessory_array_count != 0){
    foreach($accessory_array as $ac_placeholder => $ac_value) {
        if($ac_value != '') {
            $ac_placeholder = ":$ac_placeholder";
            $query->bindValue($ac_placeholder, $ac_value);
        }
    }
 }



 $results = $query->execute(); 

 $rs = $results->fetchAll(PDO::FETCH_ASSOC);

1 个答案:

答案 0 :(得分:4)

execute()方法不返回结果对象。它返回一个布尔值,true或false。

fetchAll()是PDOStatement对象的一种方法。这是一个例子:

$sth = $dbh->prepare($sql);
$sth->execute();    
$result = $sth->fetchAll();