Reputation: 3545
I am new to PHP but I like to create a script that checks if an email is in my MySQL Database, the Database name is "Fily_Registrations"
, the table is "users" and the value is called "email"
. So basically if an the email "[email protected]"
exists in my database and I call the php script like "http://path/to/[email protected]"
it should echo out "YES"
if it don't exists it should echo out "NO"
.
This is how fare I am now, but it always echoes out "NO":
<?php
$email = $_GET["email"];
$DataBase = "Fily_Registrations";
mysql_connect("server", "username", "password") or die(mysql_error());
mysql_select_db($DataBase) or die(mysql_error());
$string = sprintf("SELECT '$DataBase' FROM users WHERE email = '$email'");
$query = msql_query($string);
if($query == false) {
echo("No");
} else {
echo("Yes");
}
?>
Does anyone know how to fix this?
Upvotes: 2
Views: 30368
Reputation: 11
Not yet super safe, but better.
Prepared statements don't allow hidden mysql code execution from within parameters.
$email = mysql_real_escape($_GET["email"]);
try {
$connect = new PDO("mysql:host=server;dbname=Fily_Registrations;port=3306", "user", "password");
}catch(PDOException $e) {
print "Error!: " . $e->getMessage();
die();
}
$q= "SELECT * FROM users WHERE email = :EMAIL";
$statement = $connect->prepare($q);
$status = $statement->execute(array(":EMAIL"=>$email));
if (($status) && ($statement->rowCount() > 0))
{
echo "YES";
} else {
echo "NO";
}
Br, Kari
Upvotes: 0
Reputation: 607
Your code should be something like this:
<?php
$email = $_GET["email"];
$DataBase = "Fily_Registrations";
mysql_connect("server", "username", "password") or die(mysql_error());
mysql_select_db($DataBase) or die(mysql_error());
$string = mysql_real_escape("SELECT * FROM users WHERE email = '$email'");
$query = msql_query($string);
if($query) {
echo mysql_num_rows($query) > 0 ? "YES" : "NO";
} else {
echo("====some error===");
}
?>
mysql_num_rows : http://pt1.php.net/manual/en/function.mysql-num-rows.php mysql_real_escape: http://pt2.php.net/mysql_real_escape_string
Upvotes: 0
Reputation: 56
If database is Fily_Registrations then the query is wrong. Try this:
$email = mysql_real_escape($_GET["email"]);
$DataBase = "Fily_Registrations";
mysql_connect("server", "username", "password") or die(mysql_error());
mysql_select_db($DataBase) or die(mysql_error());
$query = "SELECT * FROM users WHERE email = '{$email}'";
$result = mysql_query($query);
echo (mysql_num_rows($result) == 0) ? 'NO' : 'YES';
mysql_query returns false if query is not correct. Read first https://www.php.net/mysql_query and consider using PDO (https://www.php.net/pdo) instead of normal mysql_query.
Upvotes: 4