PHP登录功能脚本不起作用

时间:2012-08-21 20:37:08

标签: php

看起来我的代码有些问题。我需要通过$uid$password来检查用户。我以为我说得对,但它仍然没有用,我无法弄明白。我是编程新手,非常感谢您的帮助!

更新..

以下这个功能运行正常,但是当我按照下面这样修改它时,它会给我带来错误..

public function getUser($uid, $password) {
    $result = mysql_query("SELECT * FROM users WHERE id = '$uid' AND pswd = '$password'") or die(mysql_error());

    $no_of_rows = mysql_num_rows($result);
    if ($no_of_rows > 0) {

        $result = mysql_fetch_array($result);
        return $result;    

    } else {

        return false;
    }
}

user_function.php

<?php

class DB_Functions {

    private $db;

    function __construct() {

        require_once 'db_connect.php';

        $this->db = new DB_Connect();
        $this->db->connect();
    }

    public function getUser($uid, $password) {
        $stmt = $db->prepare("SELECT * FROM users WHERE id=? AND pswd=?");
        $stmt->execute(array($uid, $password));
        return $stmt->fetch();
    }

}

?>

的index.php

<?php

if (isset($_POST['tag']) && $_POST['tag'] != '') {

    $tag = $_POST['tag'];

    require_once 'include/db_functions.php';
    $db = new DB_Functions();

    $response = array("tag" => $tag, "success" => 0, "error" => 0);

    if ($tag == 'login') {

        // check for user
        $user = $db->getUser($_POST['id'], $_POST['pswd']);

        if ($user != false) {

            $response["success"] = 1;
            $response["user"]["id"] = $user["id"];

            echo json_encode($response);

        } else {

            $response["error"] = 1;
            $response["error_msg"] = "Incorrect email or password!";
            echo json_encode($response);
        }

3 个答案:

答案 0 :(得分:3)

在类中,未正确引用属性$ db。尝试更改

public function getUser($uid, $password) {
    $stmt = $db->prepare("SELECT * FROM users WHERE id=? AND pswd=?");
    $stmt->execute(array($uid, $password));
    return $stmt->fetch();
}

public function getUser($uid, $password) {
    $stmt = $this->db->prepare("SELECT * FROM users WHERE id=? AND pswd=?");
    $stmt->execute(array($uid, $password));
    return $stmt->fetch();
}

答案 1 :(得分:3)

我认为您的数据库连接不在范围内;尝试:

public function getUser($uid, $password) {
    $stmt = $this->db->prepare("SELECT * FROM users WHERE id=? AND pswd=?");
    $stmt->execute(array($uid, $password));
    return $stmt->fetch();
}

但请参阅有关检查返回值和错误消息的注释,以查看数据库实际返回的内容。

答案 2 :(得分:2)

我不确定如何获取数据库连接句柄,但您可能需要从类属性中引用您的数据库,并将其存储为:

$this->db->prepare("SELECT * FROM users WHERE id=? AND pswd=?");