2017-03-28 83 views
0

我要選擇含有變量的SQL列「$ filter_objekt」的價值「objekt1」行OR「objekt2」 OR「objekt3」 OR值選擇數據'objekt4'。其中包含1 4列

這是我當前的查詢:

$filter_objekt = "Lorem"; 

$ergebnis = mysqli_query($db, "SELECT * FROM aktionen WHERE 
      jahr LIKE '$filter_jahr' AND 
      kunde LIKE '$filter_kunde' AND 
      kampagne LIKE '$filter_kampagne' AND 
      objekt1 LIKE '$filter_objekt' OR 
      objekt2 LIKE '$filter_objekt' OR 
      objekt3 LIKE '$filter_objekt' OR 
      objekt4 LIKE '$filter_objekt' OR 
      mediamix LIKE '$filter_mediamix' AND 
      kosten LIKE '$filter_kosten' AND 
      schulnote LIKE '$filter_schulnote' AND 
      feedback_status LIKE '$filter_feedback' 
      ORDER BY kunde ASC, aktionsname ASC"); 

此時的腳本返回表的每一行,不管它是否包含「$ filter_objekt」與否的值。

任何幫助,高度讚賞。提前致謝!

+1

使用括號來分隔'和'和'或' – HoneyBadger

回答

1

你將不得不設定的4或我們添加成塊用括號

SELECT * FROM aktionen WHERE 
     jahr LIKE '$filter_jahr' AND 
     kunde LIKE '$filter_kunde' AND 
     kampagne LIKE '$filter_kampagne' AND 
     (objekt1 LIKE '$filter_objekt' OR 
     objekt2 LIKE '$filter_objekt' OR 
     objekt3 LIKE '$filter_objekt' OR 
     objekt4 LIKE '$filter_objekt') AND 
     mediamix LIKE '$filter_mediamix' AND 
     kosten LIKE '$filter_kosten' AND 
     schulnote LIKE '$filter_schulnote' AND 
     feedback_status LIKE '$filter_feedback' 
     ORDER BY kunde ASC, aktionsname ASC 

注意,我改變了或之後objekt4到AND。

+0

該訣竅。謝謝! – hallibus

1

這是因爲你需要括號

// Your code is similar to this: 
WHERE A=$a AND B1=$x OR B2=$x OR B3=$x 

// Which actually does this: 
WHERE (A=$a AND B1=$x) OR (B2=$x) OR (B3=$x) 

// And you want: 
WHERE A=$a AND (B1=$x OR B2=$x OR B3=$x) 
在你的代碼

因此,所有你需要做的就是在你的objekt

1

OR具有較低的優先級加括號比AND,所以你需要圓括號應用全部AND條件和OR條件之一:

$ergebnis = mysqli_query($db, "SELECT * FROM aktionen WHERE 
      jahr LIKE '$filter_jahr' AND 
      kunde LIKE '$filter_kunde' AND 
      kampagne LIKE '$filter_kampagne' AND 
      (objekt1 LIKE '$filter_objekt' OR 
      objekt2 LIKE '$filter_objekt' OR 
      objekt3 LIKE '$filter_objekt' OR 
      objekt4 LIKE '$filter_objekt') AND /* I think you mean AND here, not OR, but I'm not 100% sure */ 
      mediamix LIKE '$filter_mediamix' AND 
      kosten LIKE '$filter_kosten' AND 
      schulnote LIKE '$filter_schulnote' AND 
      feedback_status LIKE '$filter_feedback' 
      ORDER BY kunde ASC, aktionsname ASC"); 
0

試試這個

$ergebnis = mysqli_query($db, "SELECT * FROM aktionen WHERE 
     jahr LIKE '$filter_jahr' AND 
     kunde LIKE '$filter_kunde' AND 
     kampagne LIKE '$filter_kampagne' AND 
     (
     objekt1 LIKE '$filter_objekt' OR 
     objekt2 LIKE '$filter_objekt' OR 
     objekt3 LIKE '$filter_objekt' OR 
     objekt4 LIKE '$filter_objekt')AND 
     mediamix LIKE '$filter_mediamix' AND 
     kosten LIKE '$filter_kosten' AND 
     schulnote LIKE '$filter_schulnote' AND 
     feedback_status LIKE '$filter_feedback' 
     ORDER BY kunde ASC, aktionsname ASC");