2015-02-10 66 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