dongxun1244 2018-03-04 12:31
浏览 39
已采纳

Mysqli只获取一行/属性[重复]

This question already has an answer here:

I have a table of users in the database, each user has an id, firstname, lastname, username and a password attribute.

I am trying to create a simple login page and I need to check if the entered password is correct for entered username.

My query looks like that:

$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = 'SELECT password FROM users WHERE username = "something"';
$result = $conn->query($sql);

Query should return a password for a specified user but I don't know how to get it.

$result->fetch_array() returns nothing in my case.

</div>
  • 写回答

2条回答 默认 最新

  • duan7264 2018-03-04 12:37
    关注

    You're thinking about this slightly the wrong way.

    There's no need to retrieve the password and then interrogate it in PHP. You can just interrogate it in your query and see if you end up with a row or not.

    Furthermore, it's wise to use prepared statements to protect against potentially malicious user input.

    $sql = 'SELECT id FROM users WHERE username = ? && password = ?';
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("ss", $_POST['username'], $_POST['password']); //<-- for example
        $stmt->execute();
        $stmt->store_result();
        if ($stmt->num_rows === 1) {
            //good login
        } else {
            //bad login
        }
        $stmt->close();
    } else
        die('DB problem...');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应