2012-12-19 72 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