错误:PDOStatement :: execute():SQLSTATE [HY093]:参数号无效:

时间:2014-05-31 10:20:56

标签: pdostatement

我写了一个这样的函数:

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,结果没有任何警告,我不知道我错在哪里。任何建议将不胜感激。

1 个答案:

答案 0 :(得分: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;

    }

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