PHP MySQL查询返回空?

时间:2015-12-09 16:36:20

标签: php mysql

<?php
// login.php

$username = trim($_POST['username']);
$password = trim($_POST['password']);

$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "myDatabase";

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Connection failed: Couldn't connect to the database");
$db = mysql_select_db($dbname, $conn) or die ("Failed to connect to MySQL: " . mysql_error());

function Login() {
    echo "<p>Login() function is called</p>"; //debug

    global $username;
    global $password;

    session_start(); //start session for the user

    if (!empty($_POST['username'])) {
        echo "<p>username is indeed not empty</p>"; //debug

        $query = "SELECT * FROM users WHERE username = '$username' AND pass = '$password'";
        $result = mysql_query($query) or die (mysql_error());
        $row = mysql_fetch_array($result) or die (mysql_error());

        while ($row = mysql_fetch_array($result)) { //debug: $row is empty
            echo $row['username'];
            echo $row['pass'];
        }

        if (!empty($row['username']) AND !empty($row['pass'])) {
            echo "<p>You succesfully logged in. Welcome " . $username . "!</p>";                
        }
        else {
            echo "<p>Wrong username and password combination</p>";
        }


    }
}

if (isset($_POST['submit']) AND $_SERVER['REQUEST_METHOD'] == 'POST') {
    echo "<p>Submit is indeed pressed and request method is POST</p>"; //debug

    Login();
}

mysql_close($conn);

?>

所以,我试图通过连接到我的MySQL数据库并检查现有的用户名和密码组合来创建一个简单的登录页面。 问题是,当我尝试检查值时,$ row数组似乎是空的,所以无论我的html表单是否传递了数据库中的用户名和密码,我总是得到错误的用户名和密码组合&#39 ;。任何人都可以更正我的查询和/或语法吗?

调用时login.php的输出是:

提交确实已按下,请求方法为POST

调用Login()函数

用户名确实不是空的

用户名和密码组合错误

0 个答案:

没有答案