2012-06-20 34 views
-3

我有PHP腳本沒有問題, 這樣的:如何簡化這個PHP IF到MySQL中?

while($row4 = mysql_fetch_array($result4)) 
{ 
if (($row4['Username'] != 'root') && ($row4['ToUpline'] == 1)){ 
if (!(($row4['Username'] != $MyUsername) && ($row4['Private'] == 1))){ 

//some other scripts here... 

}}; 

,另一方面,我已經有WHERE conditon在MySQL命令:

WHERE (NetworkTree.LeftNum <= $MyLeftNum AND NetworkTree.RightNum >= $MyRightNum) 
AND MyBlackList.HideWho IS NULL 

如何將這些PHP的條件合併成1單個SQL命令,以便我可以刪除PHP IF。上述 感謝...

+0

'PHP if'比'mysql的if'更多更快,'if'在MySQL中是不是where條件 – Sergey

+0

謝爾蓋,爲什麼你在談論的MySQL'IF' ? –

+0

在提出問題之前,你應該至少做一些*研究; SO不是你的開發人員sweatshop = p –

回答

3
WHERE 
    NetworkTree.LeftNum <= $MyLeftNum AND 
    NetworkTree.RightNum >= $MyRightNum AND 
    MyBlackList.HideWho IS NULL AND 
    Username <> 'root' AND 
    ToUpline = 1 AND 
    NOT(Username <> 'myUsername' AND 
     Private = 1) 

'myUsername'如何填補取決於你如何執行你的查詢。由於您正在使用outdated mysql_*函數,因此無法使用預處理語句,但可以使用字符串連接或sprintf(不要忘記使用mysql_real_escape_string!)。以下是如何與sprintf的做到這一點:

$query = sprintf("SELECT ... WHERE ... NOT(Username <> '%s' ...)", 
       mysql_real_escape_string($username)); 
+0

如果$ MyUsername包含字母字符,這將不起作用。 – vearutop

+0

工程就像一個魅力,兄弟!謝謝! –

+0

vearutop,它實際上是指僞SQL,但我可以看到混淆。我已經用更多的PHP方面更新了這個問題。 –

0
WHERE (NetworkTree.LeftNum <= $MyLeftNum AND NetworkTree.RightNum >= $MyRightNum) AND MyBlackList.HideWho IS NULL AND Username != 'root' AND ToUpLine = 1 AND NOT (Username != '$MyUsername' AND Private = 1)