-2

I have a simple PHP file in which I check if the users email exists in my database using the following code:

   $query = "SELECT * FROM userData WHERE email = '$email'";
   $result = mysql_query($query);

Which works perfectly fine when the user enters an email address that is in the database, however, when I want to determine if this $query is null or empty - I'm not sure which one though.

When I enter an email that isn't in the database and add the following code in below:

    if(is_null($result)){
    echo 'email not in database';
    }

the code in the {} isn't executed.

I was just wondering if you could help me out.

Hi again,

Sorry for the duplicating another post. I corrected it by using:

if(mysqli_num_rows($result) > 0)
{ 
  // a row with email exists 
} 
else 
{
  // no row with particular email exists 
}
Michael
  • 11
  • 4
  • `mysql_query` returns the executed query resource. You have to fetch data from resource or count the rows for that. – Sougata Bose Jun 23 '15 at 13:06
  • 1
    Obligatory [don't use mysql_*](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1) functions, especially if you're new :), swap over to something better now and save yourself hours of headache later on – SubjectCurio Jun 23 '15 at 13:07
  • Just a warning, this is vulnerable to [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) – Gray Jun 23 '15 at 13:11
  • there's a big difference between `is_null` and `empty`, especially in MySQL and doing a SELECT all. what you're looking for is `mysql_num_rows()` or `COUNT()`. – Funk Forty Niner Jun 23 '15 at 13:14

3 Answers3

0

Try this

$row = mysql_fetch_rows($result);
if(!$row){
      echo 'email not in database';
}

OR

$num = mysql_num_rows($result);

 if($num == 0){                                                         
    echo 'email not in database';
    }
Praveen D
  • 2,337
  • 2
  • 31
  • 43
0

You can directly check whether your query executed or not by

 if($result > 0){
    // perform some action 
 }

You should use mysqli_ instead of mysql_ as it is deprecated and will be removed in future.

what you need is mysqli_num_rows() to see if atleast 1 row was in the table or not

for reference - num_rows

if(mysqli_num_rows($result) > 0)
{ 
  // a row with email exists 
} 
else 
{
  // no row with particular email exists 
}
Meenesh Jain
  • 2,532
  • 2
  • 19
  • 29
0

You can try this too !

if(empty($result)){
    echo 'email not in database';
}

empty() will check if $result is null, or its value is 0, or if $result doesn't exists.

See here : http://php.net/manual/fr/function.empty.php

Mike
  • 1,158
  • 5
  • 22
  • 32
faflo10
  • 386
  • 5
  • 13