0

所以我有一个登录系统,我想检索登录人的名字。这是我的 php:

function verify_Username_and_Pass($un, $pwd) {
        $query = "SELECT `First Name`, Username, Password
                FROM table
                WHERE Username = :un AND Password = :pwd
                LIMIT 1";

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':un', $un);
        $stmt->bindParam(':pwd', $pwd);
        $stmt->execute();

        if ($stmt->rowCount() > 0) {
            // User exist
            return true;
            $stmt->close();
        }
        else {
            // User doesn't exist
            return false;
            $stmt->close();
        }
    }

这是具有 1 个私有变量 $conn 的类的一部分。登录工作完美,但我只想得到这个人的名字。我怎么做?

4

5 回答 5

1

首先,永远不要从数据库中获取密码,这是非常糟糕的做法。

其次,如果只返回一行,您只想接受用户是正确的。

最后bindColumn是你要找的。

<?php
function verify_Username_and_Pass($un, $pwd) {
    $query = "SELECT `First Name`, Username
              FROM table
              WHERE Username = :un AND Password = :pwd";
    // Don't limit the query to only one, if there is a chance that you can
    // return multiple rows, either your code is incorrect, bad data in the database, etc...

    $stmt = $this->conn->prepare($query);
    $stmt->bindParam(':un', $un);
    $stmt->bindParam(':pwd', $pwd);
    $stmt->execute();

    // Only assume proper information if you ONLY return 1 row.
    // Something is wrong if you return more than one row...
    if ($stmt->rowCount() == 1) {
        // User exist
        $stmt->bindColumn('First Name', $firstName);
        $stmt->bindColumn('Username', $username);
        // You can now refer to the firstName and username variables.
        return true;
        $stmt->close();
    } else {
        // User doesn't exist
        return false;
        $stmt->close();
    }
}
?>

那应该对你有用。

于 2012-10-02T17:48:12.580 回答
0

您需要将结果绑定如下

    if ($stmt->rowCount() > 0) {
        $stmt->bind_result($fname, $uname, $pwd);
        $stmt->fetch()
        echo $fname // here you get firsname

        // either you can return this $fname or store into session variable for further

        // User exist
        return true;
        $stmt->close();
    }
    else {
        // User doesn't exist
        return false;
        $stmt->close();
    }
于 2012-10-02T17:36:39.033 回答
0

在您返回 true 的部分中,您可以改为返回实际的用户数据(并且带有数据的数组无论如何都会评估为 true)。

警告的话,你应该使用散列密码。不要存储密码 y plain。

于 2012-10-02T17:37:16.747 回答
0

只是改变查询语句?

    $query = "SELECT `First Name`
            FROM table 
            WHERE Username = :un AND Password = :pwd 
            LIMIT 1"; 

如果这引发错误,您将不得不显示更多该类正在做什么来管理数据库事务

于 2012-10-02T17:26:56.357 回答
0

只需更改此行,仅First Name在查询中选择:

 $query = "SELECT `First Name`, Username, Password
            FROM table
            WHERE Username = :un AND Password = :pwd
            LIMIT 1";` 
     to 

 $query = "SELECT `First Name`
            FROM table
            WHERE Username = :un AND Password = :pwd
            LIMIT 1";`
于 2012-10-02T17:29:35.523 回答