PDO查询取决于完成的输入

PDO query depending on what inputs are completed

你好,我有一个包含 6 个字段的表单:

    Age1
    Age2
    Client type
    Destination
    Score1
    Score2

我想根据已完成的字段创建一个查询,但我不知道如何仅通过为每个可能性创建一个查询来创建查询。这些表单字段是我的 2 个表的数据库中的列。

$age1=$_POST['age1'];
$age2=$_POST['age2'];
$score1=$_POST['score1'];
$score2=$_POST['score2'];
$destination=$_POST['destionation'];
$client_type=$_POST['client_type'];

if ($age1!='' and $age2!='')
{
    $age_sql=" where TIMESTAMPDIFF(year, Bday,CURDATE())>=$age1 and TIMESTAMPDIFF(year, Bday,CURDATE())<=$age2"; 
}
if ($destination!='')
{
$dest_sql='Inner Join Leg_Client_Destinatie 
                where  Leg_Client_Destinatie.Destinatie="'.$destinatie.'"
                and Leg_Client_Destinatie.ID=Persoane.ID';  
}
$stmt = $dbh->prepare("SELECT * from Persoane $dest_sql $varsta_sql");    
                    $stmt->execute(); 
                while ($row = $stmt->fetch())
                {
                }

但这不是针对每种可能性的好的解决方案,因为可能有很多组合。你们有其他想法吗?

我设法让它工作了。我敢打赌有更优雅的方法来做到这一点,例如使用数组,但 atm 就像这样很好。如果有人有其他想法,请随时post。谢谢

$age1=$_POST['age1'];
$age2=$_POST['age2'];
$score1=$_POST['score1'];
$score2=$_POST['score2'];
$destination=$_POST['destionation'];
$client_type=$_POST['client_type'];

$sql=("SELECT * From Persoane $join WHERE Persoane.ID IS NOT NULL $join2");
if ($destination!='')
{
$join='Inner Join Leg_Client_Destination 
                ON  Leg_Client_Destination.Destination="'.$destination.'"
                ';  
$join2='and Leg_Client_Destination.ID=Persoane.ID';
} 
if ($age1!='' and $age2!='')
{
    $sql .= " AND TIMESTAMPDIFF(year, Bday,CURDATE())>=$age1 and TIMESTAMPDIFF(year, Bday,CURDATE())<=$age2"; 
}   
if ($score1!='' and $score2!='')
{
    $sql .= " AND score_T>=$score1 and score_T<=$score2"; 
}
if ($client_type!='')
{
    $sql .= " AND Client_Type=$client_type"; 
}       
                    $stmt=$dbh->prepare($sql);
                    $stmt->execute(); 
                while ($row = $stmt->fetch())
                {