基于另一个条件的PHP/MYSQL检索名称 [英] PHP/MYSQL Retrieve Name based on another criterion

查看:72
本文介绍了基于另一个条件的PHP/MYSQL检索名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have a login system and I want to retrieve the first name of the person who is logged in. Here's my 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.登录工作正常,但我只想获取此人的名字.我该怎么办?

this is part of a class who has 1 private variable $conn. The login works perfectly but i just want to get the person's first name. How do I do that?

推荐答案

首先,切勿从数据库中获取密码,这是极其糟糕的做法.

First off, NEVER grab the password from the database, that is just extremely bad practice.

第二,如果只返回一行,您只希望接受用户正确.

Second, you only want to accept the user as correct if ONLY one row is returned.

最后一个bindColumn是您要寻找的.

lastly bindColumn is what you're looking for.

<?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();
    }
}
?>

这应该对您有用.

这篇关于基于另一个条件的PHP/MYSQL检索名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆