PHP如何在多个条件下执行多个操作?

时间:2016-05-26 03:50:16

标签: php where-clause

这是我用于登录用户的当前代码:

<?php
$uName = "";
$uNameMsg = "";
$pWord = "";
$pWordMsg = "";

if(isset($_POST["submit"])){
    $uName = $_POST["username"];
    if (empty($uName)) {
        $uNameMsg = "please enter a username<br/>";
    }

    $pWord = $_POST["password"];
    if (empty($pWord)) {
        $pWordMsg = "please enter a password<br/>";
    }
}

?>

//form goes here

<?php
    require_once("conn.php");
    $sql = "SELECT username, password FROM customers
            WHERE username = $uName 
            AND password = $pWord";
    $results = mysqli_query($conn, $sql)
    or die ('Problem with query' . mysqli_error($conn));
    if (mysqli_num_rows($results) < 1) {
        echo "invalid username and password";
    } else {
        echo "query success, redirect header goes here";
    }
?>

我收到语法错误,说&#39; AND密码=&#39;条款错了。然后它说错误位于我的标记第3行,而&#39; AND密码=&#39;位于第75行。

这是我在第1行开始的代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Customer Login</title>
    <link rel="stylesheet" href="customerlogin.css">
</head>

5 个答案:

答案 0 :(得分:3)

你可以使用它。这肯定会起作用:

$sql = "SELECT username, password FROM customers
            WHERE username = '$uName' 
            AND password = '$pWord'";

答案 1 :(得分:1)

您的变量字符串连接在SQL语句中是错误的尝试下面的一个而不是您的查询代码行

$sql = "SELECT username, password FROM customers
            WHERE username = '".$uName." '
            AND password = '".$pWord."'";

答案 2 :(得分:1)

更改您的查询:

$sql = "SELECT username, password FROM customers WHERE username = '$uName ' AND password = '$pWord'";

传递字符串值时,应覆盖引号。

答案 3 :(得分:0)

在php中更改您的查询,如下所示

$sql = "SELECT username, password FROM customers 
        WHERE username = '{$uName}'  
        AND password = '{$pWord}'";

我假设username是一个字符串,因此需要使用''

将其作为字符串传递

答案 4 :(得分:0)

你错过了价值观引用'。您只能使用不带引号的数字,因为应引用值字符串。您的查询容易受到sql注入,因此要么逃避字段要么使用pdo。请参阅以下代码以转义字段。

$pWord = $conn->real_escape_string($pWord);
$uName = $conn->real_escape_string($uName);
$sql = "SELECT username, password FROM customers
        WHERE username = '$uName'
        AND password = '$pWord'";