0

我写了一个这样的函数:

function tim_kiem($tenchu,$sohieutoba,$sothututhu,$gia_dat){
        global $dbh;
        $where="1=1";
        $tenchu = "%".$tenchu."%";

        if($tenchu<>""){

        $where=$where." and tenchu like :tenchu";
        }
        if($sohieutoba<>0){
        $where=$where." and (sohieutoba=:sohieutoba)";
        }
        if($sothututhu<>0){
        $where=$where." and (sothututhu=:sothututhu)";
        }
        if($gia_dat<>""){
        $where=$where." and gia_dat=:gia_dat";
        }
        $sql="SELECT * FROM mybinh WHERE ".$where;


        $sth=$dbh->prepare($sql);
        $sth->bindValue(':tenchu', $tenchu);
        $sth->bindValue(':sohieutoba', $sohieutoba);
        $sth->bindValue(':sothututhu', $sothututhu);
        $sth->bindValue(':gia_dat', $gia_dat);

        $sth->execute();

        $row=$sth->fetch(PDO::FETCH_ASSOC);
        return $row;

    }

结果还可以,但会附加警告

“PDOStatement::bindValue(): SQLSTATE[HY093]: 无效参数号: :sohieutoba ...”

,如果我同时输入$sohieutoba$sothututhu,结果没有任何警告,我不知道我错在哪里。任何建议将不胜感激。

4

1 回答 1

0

当您使用条件来创建查询时,您还应该根据您的条件绑定值。现在您可以只使用一个条件if($tenchu<>""),但绑定所有 4 个参数是什么问题。

最简单的解决方案是简单地重复您的陈述:

function tim_kiem($tenchu,$sohieutoba,$sothututhu,$gia_dat){
        global $dbh;
        $where="1=1";
        $tenchu = "%".$tenchu."%";

        if($tenchu<>""){

        $where=$where." and tenchu like :tenchu";
        }
        if($sohieutoba<>0){
        $where=$where." and (sohieutoba=:sohieutoba)";
        }
        if($sothututhu<>0){
        $where=$where." and (sothututhu=:sothututhu)";
        }
        if($gia_dat<>""){
        $where=$where." and gia_dat=:gia_dat";
        }
        $sql="SELECT * FROM mybinh WHERE ".$where;

        $sth=$dbh->prepare($sql);
        if($tenchu<>""){        
           $sth->bindValue(':tenchu', $tenchu);
        }
        if($sohieutoba<>0){
          $sth->bindValue(':sohieutoba', $sohieutoba);
        }
        if($sothututhu<>0){
           $sth->bindValue(':sothututhu', $sothututhu); 
        }
        if($gia_dat<>""){
           $sth->bindValue(':gia_dat', $gia_dat);
        }

        $sth->execute();

        $row=$sth->fetch(PDO::FETCH_ASSOC);
        return $row;

    }

然而,这不是最优雅的方式。例如,您可以仅使用一个条件并创建数组,然后在循环中绑定您的参数

于 2014-05-31T10:44:57.260 回答