This is my form:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="register_ajax.php" method="get">
<input type="text" name="email">
<input type="submit" value="test">
</form>
</body>
</html>
This is my php code:
<?php
$dbc = mysqli_connect("localhost","root","*******","continental_tourism") OR die(mysqli_connect_error());
$email = $_GET['email'];
$query = "SELECT email FROM customer_info WHERE email = '$email' ";
$r = mysqli_query($dbc, $query) OR die(mysqli_error($dbc));
if($r)
echo "Email address exists!";
else
echo "sss";
?>
If I enter a correct(Existing email on db) $r
is true. But if I enter non existing email, then also $r
is true. Why is that? Basically I want to detect the empty set. How can I do it?
Thanks!
$r
will only be false if there was SQL error. Otherwise it will always return a resource ID even if no rows are returned by your SELECT statement.
Use mysqli_num_rows()
to count how many rows are returned. Zero means no one is using that email address.
if(mysqli_num_rows($r))
echo "Email address exists!";
else
echo "sss";
mysqli_query()
will always returns a MySQLi result resource if the query was successful. A resource will always evaluate to TRUE
when tested as a boolean.
A successful query is not necessarily one that returns results, it is simply a query that did not fail. Queries are considered to have failed when there is an error, for example a syntax error or a processing error within the MySQL server - which case they will return FALSE
. But a query that finds no results is still a successful query.
You need to use mysqli_num_rows()
to determine whether the query found any results:
<?php
$dbc = mysqli_connect("localhost","root","longhorn","continental_tourism") OR die(mysqli_connect_error());
$email = $_GET['email'];
$query = "SELECT email FROM customer_info WHERE email = '$email' ";
$r = mysqli_query($dbc, $query) OR die(mysqli_error($dbc));
if(mysqli_num_rows($r) > 0)
echo "Email address exists!";
else
echo "sss";
?>
mysqli_query
will return a result object on success and false
on failure. No rows selected is not considered failure. You can use mysqli_num_rows
to check the number of rows returned.
One needs to test to see if $r
is true, and if row count is greater than 0.
The following works:
if ($r and mysqli_num_rows($r) > 0) {
echo "rows exist"; } else {
echo "rows don't exist"; }