2012-12-19 73 views
1

我可以在IF語句中執行WHERE子句嗎?SQL條件中的WHERE語句

就像我想是這樣的:?

 $SQL = mysql_query("SELECT * FROM `table` ORDER BY `row` DESC"); 
    $rows = mysql_fetch_array($SQL); 
    $email = $_SESSION['email_of_user']; 

     if($rows["row"] == "1" WHERE `row`='$email' : ?> (Pulls the logged in user's email) 
     Edit Server 
     <?php else : ?> 
     Add Server 
     <?php endif; ?> 

我需要(」裏的WHERE語句是因爲我試過了,它似乎並沒有工作...

,或者可以我在where子句中使用了if條件嗎?不知道所有這些條款如何糾正我,如果我錯了...

+0

'WHERE'是SQL而不是PHP語法。如果你可以顯示更多關於'$ row'的信息(存儲在它裏面;它是如何填充的),可能有一種方法可以在PHP命名法中執行任務(如果不在SQL查詢本身內)。 –

+0

好吧,添加了更多關於行的信息,但它幾乎只是提取$ SQL。 – user1907276

+0

'row'怎麼可能是'1' _and_'$ email'(除非'$ email = 1')? –

回答

2

您不能混合使用查詢語句與PHP語句。提取期望的結果和chec的查詢k如果該查詢中有任何行,則爲k。

我會告訴你一個例子:

$query = "SELECT * FROM `TABLE_NAME` WHERE `field` = '1' && `email`='$email'"; //Create similar query 
$result = mysqli_query($query, $link); //Query the server 
if(mysqli_num_rows($result)) { //Check if there are rows 
    $authenticated = true; //if there is, set a boolean variable to denote the authentication 
} 

//Then do what you want 
if($authenticated) { 
    echo "Edit Server"; 
} else { 
    echo "Add Server"; 
} 

由於阿龍已經顯示出這樣的努力,以鼓勵安全的代碼在我的例子。這是你如何安全地做到這一點。 PDO庫提供了以安全方式將參數綁定到查詢語句的選項。所以,這裏是如何做到這一點。

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); //Create the connection 

//Create the Query Statemetn 
$sth = $dbh->prepare('SELECT * FROM `TABLE_NAME` WHERE field = :field AND email = :email'); 

//Binds Parameters in the safe way 
$sth -> bindParam(':field', 1, PDO::PARAM_INT); 
$sth -> bindParam(':email', $email, PDO::PARAM_STRING); 

//Then Execute the statement 
$sth->execute(); 

$result = $sth->fetchAll(); //This returns the result set as an associative array 
+0

是的,我有一個查詢,它抓住了表,但無論如何,如果具有該特定電子郵件的玩家有一個1在某一行中沒有得到添加服務器,只有編輯? – user1907276

+0

@ user1907276,你可以像'\'field \'='1'和\'email \'='$ email'' – Starx

+0

這樣的條件結合使用已經有一段時間了,因爲我已經使用了PHP,但是沒有其他方法注入參數而不允許SQL注入?即使作爲初學PHP程序員,它似乎是我能夠輕鬆掌握的東西。 – AaronLS