简体   繁体   中英

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

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM