dongxun1244 2018-03-04 04: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 04: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部