php 错误:PDO语句::execute():SQL状态[HY093]:无效的参数编号:

w41d8nur  于 2022-12-10  发布在  PHP
关注(0)|答案(1)|浏览(182)

我写了这样一个函数:

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;

    }

结果正常,但附加警告
“PDO语句::绑定值():SQL状态[HY093]:无效的参数编号::sohieutoba...”
,如果我同时输入$sohieutoba$sothututhu,结果没有任何警告,我不知道我错在哪里.任何建议将不胜感激.

tzcvj98z

tzcvj98z1#

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

    }

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

相关问题