将 SQL 查询更改为带条件的准备语句

Change SQL Query to a prepared statement with condition

我正在尝试将此查询更改为带有准备好的语句的查询,但由于条件原因我遇到了一些问题。 这是我的基本查询:

function ResponseByQuery($link,$idQuery,$Boutique=null, $agency=null){
    $from_agence = "";
    $req_agence = "";
    $req_boutique = "";

    if($Boutique!=null){
        $req_boutique = " AND C.idUser ='" . $Boutique . "' ";  
    }

    if($agency!=null){
        $from_agence = ", infos_client as IRC2";
        $req_agence = " AND IRC.idClient = IRC2.idClient                    
                    AND IRC2.valueInfo = '". $agency."'";

    }           
    $sql = "SELECT  distinct(C.idClient), R.indiceRequete
            FROM    `infos_client` as IRC, client as C, user as U, requete as R ".$from_agence." 
            WHERE   IRC.idQuery='" . $idQuery . "'".
            $req_boutique. 
            "AND IRC.idCl = C.idCl          
            AND C.idUser=U.idUser".$req_agence;     
    $result = mysqli_query($link,$sql) or die("Query (- $sql -) failed");
    $count = mysqli_num_rows($result);   
}

我改成了这个:

function ResponseByQuery($link,$idQuery,$Boutique=null, $agency=null){
    $from_agence = "";
    $req_agence = "";
    $req_boutique = "";

    if($Boutique!=null){
        $req_boutique = " AND C.idUser ='" . $Boutique . "' ";  
    }

    if($agency!=null){
        $from_agence = ", infos_client as IRC2";
        $req_agence = " AND IRC.idClient = IRC2.idClient                    
                    AND IRC2.valueInfo = '". $agency."'";

    }           
    $sql = "SELECT  distinct(C.idClient), R.indiceRequete
            FROM    `infos_client` as IRC, client as C, user as U, requete as R ".$from_agence." 
            WHERE   IRC.idQuery =?".
            $req_boutique. 
            "AND IRC.idCl = C.idCl          
            AND C.idUser=U.idUser".$req_agence;     
    $stmt = $link->prepare($sql);
    $stmt->bind_param('i', $idQuery);
    $result = $stmt->execute() or die("Query (- $sql -) failed");
    $result = $stmt->get_result();
    $count = mysqli_num_rows($result);   
}

但我不知道如何将 conditions($req_boutique,$req_agence) 更改为准备好的语句?

您可以将 $req_boutique$req_agence 条件中的内联变量替换为占位符,然后有条件地将值绑定到它们:

if($Boutique!=null){
    $req_boutique = " AND C.idUser = ? ";  
}

if($agency!=null){
    $from_agence = ", infos_client as IRC2";
    $req_agence = " AND IRC.idClient = IRC2.idClient                    
                AND IRC2.valueInfo = ? ";

}           
$sql = "SELECT  distinct(C.idClient), R.indiceRequete
        FROM    `infos_client` as IRC, client as C, user as U, requete as R ".$from_agence." 
        WHERE   IRC.idQuery =? ".
        $req_boutique. 
        "AND IRC.idCl = C.idCl          
        AND C.idUser=U.idUser".$req_agence;     
$stmt = $link->prepare($sql);
$types = 'i';
$vars = [$idQuery];
if ($Boutique != null) {
    $types .= 's';
    $vars[] = $Boutique;
}
if ($agency!= null) {
    $types .= 's';
    $vars[] = $agency;
}
$stmt->bind_param($types, ...$vars);