How to use mysqli prepare statement to login with email or username (Not PDO)?

落花浮王杯 提交于 2021-02-08 10:37:21

问题


I have saw many answer about php login with username or email, but I can't find the resolution of "Mysqli Prepare Statement", all of them used PDO...

My question is, why I can't use two ? to select username or email?

My code is here:

Database

table user
--id int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
--username varchar(20),
--password varchar(255),
--email varchar(30),

html

<form action="login.php" id="login_form" method="post">
    <input type="text" name="account" placeholder="username or email" />
    <input type="password" name="password" placeholder="password" />
    <div class="login_submit">
      <button type="submit" name="submit">Login</button>
    </div>
</form>

PHP

<?php
$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, DB_PORT);
$con->query('SET CHARACTER SET utf8');

if (isset($_POST['submit'])) {
    $account = $_POST['account'];
    $get_password = $_POST['password'];
    $login_query = 'SELECT username,password,email FROM user WHERE username = ? OR email = ?';
    $login_stmt = $con->stmt_init();

    if ($login_stmt->prepare($login_query)) {
        $login_stmt->bind_param('ss', $account, $account);
        $login_stmt->execute();
        $login_stmt->bind_result($username, $password, $email);
        $login_result = $login_stmt->get_result();
        while ($login_row = $login_result->fetch_assoc()) {
            $check_password = $login_row['password'];
        }
    } else {
        echo 'Login Error';
        exit();
    }

if ($login_result->num_rows == 0) {
    $account_error = $lang_account_not_exist;
    $login_permit = false;
} elseif (!password_verify($get_password, $check_password)) {
    $password_error = $lang_wrong_password;
    $login_permit = false;
}

EDIT

bind_result($username, $password, $email);

回答1:


Your problem is probably NOT on

$login_stmt->bind_param('ss', $account, $account);

As you'd think.

This looks fine, unless your $_POST['account'] is an array and not a single variable, which I doubt. In this case it will fail there. But your WHERE statement and bindparam looks correct

However this is not correct :

$login_stmt->bind_result($password);

Because you try to bind only one variable and you have 3 columns returned in your SELECT statement (SELECT username,password,email )

Since you don't really need the email and username in your code, just change your query like this:

$login_query = 'SELECT password FROM user WHERE username = ? OR email = ?';

and it should work



来源:https://stackoverflow.com/questions/50136193/how-to-use-mysqli-prepare-statement-to-login-with-email-or-username-not-pdo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!