Tom
Tom

Reputation: 3

Checking if username already exists in db prepared statement

I am trying to check if a posted username already exists in my database. I am not sure where I am going wrong. The other conditions below are working correctly. When I submit the form I always receive "Username taken" even when no such name exists in my db. Any help would be greatly appreciated. Thanks!

$username = $_POST['username'];

 $stmt = $mysqli->prepare('SELECT COUNT(*) FROM users WHERE username = ?');

$stmt->bind_param('s', $username);

$stmt->execute();

$stmt->store_result();

 if(isset($_POST["submit"]))
 {

      if(empty($_POST["username"]))
      {
          echo '<script>alert("Username field empty")</script>';

     } else if(empty($_POST["password"])) {
          echo '<script>alert("Password field empty")</script>';

     } else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          echo '<script>alert("Incorrect email format")</script>';

     } else if($stmt->num_rows > 0) {
     echo '<script>alert("Username taken")</script>';

Upvotes: 0

Views: 458

Answers (1)

Shadow
Shadow

Reputation: 34232

selec count(*) ... always returns 1 record, with the count. So, when you check else if($stmt->num_rows > 0), then it always returns true. You should check the value returned by count, not the number of records.

Upvotes: 1

Related Questions