如果在SQL中有条件,则在WHERE语句中

时间:2012-12-19 02:15:46

标签: php sql

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

1 个答案:

答案 0 :(得分: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库提供了以安全的方式将params绑定到查询语句的选项。所以,这是如何做到的。

$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