0

Does anybody know how to correct this code so that it identifies whether an email already exists in the database and display an error. It is currently displaying the error message even if the email DOES NOT exist in the database -- therefore the form is not getting submitted:

$email = $_POST['email'];
//prepare and set the query and then execute it
$stmt = $conn2->prepare("SELECT COUNT(email) FROM users WHERE email = ?");
$stmt->bind_param('s', $email);
$stmt->execute();

// grab the result
$stmt->store_result();

// get the count
$numRows = $stmt->num_rows();

if( $numRows )
{
$errors = true;
 echo "<p class='red'>Email is already registered with us</p>";
}
else


//if we have no errors, do the SQL
MPelletier
  • 16,256
  • 15
  • 86
  • 137
user1227124
  • 369
  • 2
  • 3
  • 11

3 Answers3

1

$numRows = $stmt->num_rows(); will always return one because you're only selecting one row (even if the value of COUNT(email) is 0)

$row = $stmt->fetch()
echo $row[0]; // result of COUNT(email)
Mike B
  • 31,886
  • 13
  • 87
  • 111
1

Like this mate:

$stmt = $mysqli->prepare("SELECT COUNT(email) FROM users WHERE email = ?");
$stmt->bind_param('s',$email);
$stmt->execute();
$stmt->bind_result($count);
while($stmt->fetch()){}

if(!empty($count)){ echo "Already Registered"; }

Using:

// grab the result
$stmt->store_result();

Is only used if you left another connection open previously.

Using:

// get the count
$numRows = $stmt->num_rows();

Is a silly approach when you are just counting id anyway.

Dan Kanze
  • 18,485
  • 28
  • 81
  • 134
0

select count(*) will always return 1 row...

You need to either use SELECT * or adapt the code to query the results back from the SQL statement

Sparky
  • 14,967
  • 2
  • 31
  • 45