Reputation: 11
This should be easy but I'm can't make it work. The idea is to look for an email adress posted from a form. If it exists echo something and if not echo something else.
My code is:
<?php
//MySQL Database Connect
mysql_connect("localhost", "********", "**********")
or die("Unable to connect to MySQL");
//get data from form
$email=$_POST['email'];
//ask the database for coincidences
$result = mysql_query("SELECT email FROM pressmails WHERE email='.$email.'");
$num_rows = mysql_num_rows($result);
if($num_rows < 0){
echo "The user is registered";
} else {
echo "The user is not registered";
}
//Close database connection
mysql_close();
?>
Upvotes: 0
Views: 6802
Reputation: 2841
(assuming you get your syntax errors corrected) isn't the logic of this backwards?
if($num_rows < 0){
echo "The user is registered";
} else {
echo "The user is not registered";
}
if the user is registered their email is in the database and the query returns one or more rows
try
if($num_rows){
echo "The user is registered";
} else {
echo "The user is not registered";
}
Upvotes: 0
Reputation: 53246
You do not need the concatenation identifiers, since wrapping a literal in "
will automatically parse variables into the string:
$result = mysql_query("SELECT email FROM pressmails WHERE email='$email'");
You should watch out, mind you. Doing the above represents a significant SQL injection vulnerability. You should consider sanitizing $email
as a minimum. Also see my comment about the mysql_*
functions in PHP.
From the Docs:
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_close() PDO: Assign the value of NULL to the PDO object
Upvotes: 1
Reputation: 41954
You should end the string by using a closing quote (if you started the string with "
you must end the string with "
too, same for '
).
And do not forget to use mysql_real_escape_string
, otherwise the script is not safe.
The script will become something like this:
// save the query in a variable, so we can echo it to debug when it doesn't work as expected
$sql = "SELECT email FROM pressmails WHERE email='".mysql_real_escape_string($email)."'";
$result = mysql_query($sql);
Upvotes: 1
Reputation: 1299
You are not concatenating string properly.
$result = mysql_query("SELECT email FROM pressmails WHERE email='.$email.'");
should be
$result = mysql_query("SELECT email FROM pressmails WHERE email='".$email."'");
Upvotes: 3