Error: PDOStatement::execute(): SQLSTATE[HY093]: Invalid par


Error: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number:

我写了这样一个函数:

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;
    }

结果是ok的,但是它附加了一个警告

"PDOStatement::bindValue(): SQLSTATE[HY093]:无效参数号:: sohieutoba…"

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

在使用条件创建查询时,还应该根据条件绑定值。现在你可以只使用一个条件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;
    }

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