-6

My function should return number of rows with email like '$email'. But whey return 0 all the time, although in database i have rows with email like I insert in variable '$email'. What could be the reason?

function checkMail($email){     
    $email = mysql_real_escape_string($email);
    $sql = "SELECT COUNT(*) FROM users WHERE email='$email'";       
    return mysql_query($sql);   
}
zhuzhik
  • 41
  • 9
  • 1
    You say `like`... but you use `=`. Stop using mysql, the functions are deprecated. Use mysqli or PDO, and either pass a connection resource into the function or acquire it globally. – scrowler Dec 19 '13 at 20:55
  • change the return to `return mysql_query($sql) or die("MySQL error for $sql:" . mysql_error());` It will show you an error message – beardhatcode Dec 19 '13 at 20:55

3 Answers3

0
function checkMail($email){     
  $email = mysql_real_escape_string($email);
  $sql = "SELECT COUNT(*) FROM users WHERE email='$email'";       
  $resource=mysql_query($sql);
  $row=mysql_fetch_array($resource);
  return $row[0];   
}
symcbean
  • 47,736
  • 6
  • 59
  • 94
0

You aren't returning a result, you're returning a query resource:

function checkMail($email){     
    $email = mysql_real_escape_string($email);
    $sql = "SELECT COUNT(*) as emailCount FROM users WHERE email='$email'";       
    $query = mysql_query($sql) or die(mysql_error()); // show error if one happens
    return mysql_fetch_assoc($query);
}

This will return an associative array containing your results (if it succeeds), and you should be able to access your count by:

$res = checkMail('your@email.com');
$count = $res['emailCount'];

Side note:

mysql functions are deprecated, you should use mysqli or PDO syntax: https://stackoverflow.com/a/13944958/2812842

Community
  • 1
  • 1
scrowler
  • 24,273
  • 9
  • 60
  • 92
-1

To fetch the count use:

mysql_query($sql)
$row = mysql_fetch_assoc($result);
return($row[0]);

The funny thing is that mysql_query return 0, which indicates query fail. Check the corresponding error message with:

echo mysql_error();
vigour
  • 45
  • 1
  • 8