过滤数据pdo

时间:2016-08-16 14:59:24

标签: php sql pdo

我想做的就是这个。 Search Filtering with PHP/MySQL

  <?php 
        require 'con.php';

        $minage     = $_POST['data'][0];
        $maxage     = $_POST['data'][1];
        $gender     = $_POST['data'][2];
        $religion   = $_POST['data'][3];

        $query = "SELECT CONCAT(firstname, ' ', middlename, ' ', lastname, ' ', extension_name) as fullname, TIMESTAMPDIFF(YEAR, birthday ,NOW()) as age FROM mytable";
$filter = array();


       if($gender != -1){
           $gender = substr($gender, 1, -1);
           $filter[] = "gender = :gender";
       }
       if($religion != -1){
            $filter[] = "religion = :religion";
       }

       if(count($filter) > 0){
           $query .= " WHERE " . implode(' AND ', $filter);
           $sql = $connection->prepare($query);
     ->    $sql->bindParam(':gender', $gender, PDO::PARAM_STR);
     ->    $sql->bindParam(':religion', $religion, PDO::PARAM_STR);
           $sql->execute();
           $res = $sql->fetchAll();
      }else{
           $sql = $connection->prepare($query);
           $sql->execute();
           $res = $sql->fetchAll();
      }
  ?>

   <?php foreach($res as $row): ?>
         <div><?php echo $row['fullname'];?></div>
   <?php endforeach; ?>

当我在下拉列表中选择性别和宗教时,结果很好。

但是当我只选择一个时,让我们说性别,我收到了一个错误:

  

绑定变量的数量与令牌数量不匹配

我对$sql->bindParam(...);的放置位置感到有些困惑。我想这是我错误的原因?或者如果还有更多错误&#39;或者如果有什么不对的,请纠正我。先感谢您。

2 个答案:

答案 0 :(得分:1)

只需将值与占位符一起添加,然后将它们发送给执行

if($gender != -1){
   $filter[] = "gender = ?";
   $values[] = $gender;
}
if($religion != -1){
    $filter[] = "religion = ?";
    $values[] = $religion;
}
$query .= " WHERE 1 AND " . implode(' AND ', $filter);
$stmt = $connection->prepare($query);
$stmt->execute($values);

答案 1 :(得分:0)

绑定也应该是有条件的:

if($gender != -1){
           $filter[] = "gender = :gender";
       }
       if($religion != -1){
            $filter[] = "religion = :religion";
       }

       if(count($filter) > 0){
           $gender = substr($gender, 1, -1);
           $query .= " WHERE " . implode(' AND ', $filter);
           $sql = $connection->prepare($query);
           if($gender != -1){
         $sql->bindParam(':gender', $gender, PDO::PARAM_STR);
           }
           if($religion != -1){
         $sql->bindParam(':religion', $religion, PDO::PARAM_STR);
           }
           $sql->execute();
           $res = $sql->fetchAll();
      }else{

这是一个非常糟糕的代码,试图让它更具可读性