3

So it is my first day working in MYSQLi(converting over from mysql), and I am having trouble with my login script where I check for duplicate emails:

Here is what i've got:

$email = mysqli_escape_string($_POST['email']);

$stmt=$mysqli->prepare("SELECT username from users WHERE email=?");
$stmt->bind_param('s',$email);
$stmt->execute(); 
$nrows1=$mysqli->num_rows;
echo $nrows1;
$stmt->close();

if ($nrows1>0) {
    $_SESSION['loggedin'] = false;
    $_SESSION['error'] = "Our records indicate that there is already an account registered with that email. Please use the 'forgot your password' link below if you cannot remember your password.";
    header('Location: registration.php');
    echo "running insisde duplicate email";
        exit();
}

I keep returning 0 rows or an empty variable when echoing $nrows1. When I enter the query directly in sql, it works fine. I seem to be following the documents and have tinkered a bunch with it.

I also used the affected rows function, but I do not believe that is appropriate for a SELECT statement, correct?

Sincere thanks for any help, it is greatly appreciated.

ambe5960
  • 1,870
  • 2
  • 19
  • 47

1 Answers1

5

After executing, you need to use mysqli_stmt_store_result() to get the result set, so it will know how many rows there are. Also, you should apply $num_rows to the statement, not the connection.

$stmt->execute();
$stmt->store_result();
$nrows1 = $stmt->num_rows;
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks a bunch. I was wondering about the double escaping as well, and that actually turned out to be part of the problem as well. The stored result worked great. – ambe5960 Dec 15 '14 at 23:02
  • 1
    That's right. You don't need to escape the data if you use `bind_param`. – Barmar Dec 16 '14 at 03:55