-2

I am trying to validate if $email exists in my database. I am 100% sure $email has not been registered before, yet count($results) is returning 1 and $results['email'] is returning an empty string.

I have looked at other examples on how to code a query to the database. I like it this way, so I haven't tried a different way to code it.

In my database I have only 1 email registered and it is different from $email.

Context: Using Netbeans, XAMPP, MySQL Workbench

     $records = $conn->prepare('SELECT * FROM users WHERE email = :email');
     $records->bindParam(':email',$email);
     $records->execute();
     $results = $records->fetch(PDO::FETCH_ASSOC);

     IF(count($results) == 0){ 

     ....

4 Answers4

1

I think variable $result is false.

So count($result) is count(false) is 1.. motto of the story don't use count there.

Your code should be something like this.

$records = $conn->prepare('SELECT * FROM users WHERE email = :email');
$records->bindParam(':email',$email);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);

/* Check with */ 
if ($result === false) {
 // Email doesn't exists
}

/* Or check with  */ 
if (!is_array($result)) {
  // Email doesn't exists
} 
Raymond Nijland
  • 11,488
  • 2
  • 22
  • 34
1

Just for clarity, how to make your code less bloated

 $stmt = $conn->prepare('SELECT 1 FROM users WHERE email = ?');
 $stmt->execute([$email]);
 $emailFound = $stmt->fetchColumn();

 if($emailFound) {
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • I'm new to this. I learned somewhere that what I was doing was a best practice. But then again, I had also two variables :email, and $email named almost the same and that might have caused confusion. – Andrew Redican Nov 28 '16 at 03:08
0

Since an empty array is a false value you can just check it.

$records = $conn->prepare('SELECT * FROM users WHERE email = :email');
$records->bindParam(':email',$email);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
if(!$results) echo 0;

or

if($results->rowCount() == 0){}
Mayank
  • 26
  • 2
0

My mistake was I was using this:

if(count($results) == 0){ ...

to validate if there were any records. You can just simply use the code below. The reason being, result$ was already returning 'false' and technically I was counting a boolean value.

IF($result === false){  ...