2015-02-10 63 views
0

你好,我有6个领域的一种形式:PDO查询完成

Age1 
    Age2 
    Client type 
    Destination 
    Score1 
    Score2 

我想基于完成哪些领域创建一个查询,我不知道如何只有一个创造通过为每个posibility创建一个查询。这些表单域是我的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()) 
       { 
       } 

但这不是一个很好的解决方案,因为可以有很多组合。你们中的任何一个有另一个想法?

+0

这就是你可以做的所有事情:根据用户选择的内容动态建立你的查询字符串。否则你就会陷入写难以置信的丑陋/巨大的查询中,这些查询包含处理所有可能的选项组合的逻辑。 – 2015-02-10 16:40:54

+0

好吧,但检查我的例子让我们说,我的目的地和年龄完成,然后在年龄sql我需要'和'而不是'where'因为我在'$ dest_sql'上使用'where'' – user3463807 2015-02-10 16:43:29

+0

是的。如果您动态构建查询,那么您必须确保构建语法VALID查询。 – 2015-02-10 16:44:12

回答

0

我设法让它工作。我敢打赌,有更优雅的方式来做到这一点,例如数组,但atm就像这样。如果有人有另一个ideea随时发布它。 Thnx

$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()) 
       { 
+0

好吧,你也打开了自己的SQL注入,因为你没有准备你的参数。 – prodigitalson 2015-02-10 18:18:13

+0

我知道我在绑定参数之前使用了代码,无论如何这个代码都在登录:p'$ stmt-> bindParam(':age1',$ age1);' – user3463807 2015-02-10 18:42:59