1

我可以在 IF 语句中执行 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 条件吗?不确定所有这些术语,如果我错了,请纠正我......

4

1 回答 1

2

您不能将查询语句与 PHP 的语句混淆。而是编写一个提取所需结果的查询,并检查该查询中是否有任何行。

我将向您展示一个示例:

$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";
}

由于 Aaron 在我的示例中表现出鼓励安全代码的努力。以下是您可以安全地执行此操作的方法。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
于 2012-12-19T02:21:00.503 回答