-4

看起来我对这段代码有一些问题。我需要通过$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;
    }
}

用户函数.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();
    }

}

?>

索引.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);
        }
4

3 回答 3

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();
}
于 2012-08-21T20:41:23.350 回答
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();
}

但是请参阅有关检查返回值和错误消息的评论,以了解数据库实际返回的内容。

于 2012-08-21T20:42:08.530 回答
2

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

$this->db->prepare("SELECT * FROM users WHERE id=? AND pswd=?");
于 2012-08-21T20:41:48.577 回答