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 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码