This question already has answers here:
Check email exist with php mysqli [duplicate]
(2 answers)
Check if row exists in the database before inserting
(3 answers)
Closed 1 year ago.
I'm trying, as many others here have before me, to check if an email already exists in my database during account registration on my website, using PHP to interact with a MySQLi database. I've tried using as many guides as I could find here but still no luck.
Below is the code I originally wrote to insert the email of users into my database upon registration:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$database = new mysqli("localhost", "user", "dbpw", "dbname");
if($database->connect_error){
die( "Error connecting:" . $database->connect_error);
}
$email = $database->real_escape_string(htmlspecialchars($_POST["email"]));
$query = "SELECT email FROM Users WHERE email =$email";
$result = $database->query($query);
$numOfRows = $database->num_rows($result);
if($numOfRows > 0){
echo "Email already exists in our database.";
}else{
$query = "INSERT INTO Users (email) VALUES ('" . $email . "');
if(!$database->query($query)){echo("<p>Unable to add user for query: " . $query . " <br /> Error: " . $database->errno . " " . $database->error);}}
Prior to inserting the email check (the if($numOfRows) statement), my database was being updated properly.
However, after adding my attempted email check, the page completely broke. My database wouldn't update with unique passwords, and it wouldn't display the echoed message "Email already exists in our database" if the email was a duplicate. The page would load, but with just the basic header, footer, and background CSS I have linked to every page.
Instead of using
$numOfRows = $database->num_rows($result);
Use
if($result ->num_rows)
{
}
You need to add single quotation marks around the email variable. Like this '$email'. Check the below code.
$query = "SELECT email FROM Users WHERE email = '$email'";
And you need to edit your conditional statement to check whether its greater than or equal to 0 or you can just use variable as boolean in condition block.
Related
I'm currently coding a registration script in PHP and my problem is that the data is still inserted into the database even though it already exists. It's probably some silly mistake or I need some else{} statement or I don't really know. The thing is that even though the email already exists in the database it stills enters it.
It does display the error just fine.
if(filter_var($email,FILTER_VALIDATE_EMAIL)){
$email = filter_var($email,FILTER_VALIDATE_EMAIL);
$email_check = mysqli_query($con, "SELECT email FROM database WHERE email='$email'");
$num_rows = mysqli_num_rows($email_check);
if($num_rows>0){
echo "The email is already in use.<br>";
}
$query = mysqli_query($con,"INSERT INTO database VALUES (NULL,'$username','$name','$email','$pwh','$date')");
}
?>
If the email is already in use it displays the echo "The email is already in use." just fine, yet it still inserts it. What am I missing? I already tried using 'else' variable yet nothing helped.
Your if only echo something, then you do the INSERT no matter what. Some solution :
if(filter_var($email,FILTER_VALIDATE_EMAIL)){
$email = filter_var($email,FILTER_VALIDATE_EMAIL);
$email_check = mysqli_query($con, "SELECT email FROM database WHERE email='$email'");
$num_rows = mysqli_num_rows($email_check);
if($num_rows>0){
echo "The email is already in use.<br>";
}
// ADD A ELSE SO YOU INSERT IF YOU HAVE NOTHING
else {
$query = mysqli_query($con,"INSERT INTO database VALUES (NULL,'$username','$name','$email','$pwh','$date')");
}
}
Now you can prevent it from your database too :
Add a UNIQUE INDEX on the column email from your table database
Use INSERT IGNORE now, so it will insert if the email is not used and ignore if email is already used
And last, use prepare statement and bind param to avoind SQL injection !
Hope it helps
Your if is fine, but you then proceed to always do the insert. This is because you have put it outside the if.
what you should do is :
if(!$num_rows <= 0){
<insert statement>;
}
else {
echo "The email is already in use.<br>";
}
write this statement inside else block
else
{
$query = mysqli_query($con,"INSERT INTO database VALUES (NULL,'$username','$name','$email','$pwh','$date')");
}
I am working on a code for my music site. This is part of the registration phase. I want the code to check the database for any existing email addresses, if found, print " email ("email address") already exists, but if not found, then insert the information into the database. The code seems to run if an email address similar to the one submitted from the html form is found, but if there is no email found, the system stops and does nothing after that. Can someone help me figure out where i went wrong.
if ($_POST['submit2']){
$fname = $_POST['Fname'];
$sname = $_POST['Sname'];
$email = $_POST['Emailaddress'];
$pass = $_POST['newpassword'];
$sql= "select * from cust_information where email = '$email';";
$results = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$row = mysqli_fetch_array($results) or die(mysqli_error($conn));
if (count($row) < 0)
{
$sql2 = "insert into cust_information (firstName, lastName, email, password) values(`$fname`, `$sname`, `$email`, `$pass`)";
$results2 = mysqli_query($conn, $sql) or die(mysqli_error($conn));
if (!$results2){
echo "successfully uploaded cust";
}
}else{
echo "email <strong>".$row["email"]. " </strong> already Exist";
}
}
You are checking whether the number of results returned is less than 0. The length of an array (and the number of results found) cannot ever be less than 0. The manual shows that mysqli_fetch_array returns null if no results are found, thus you want to check for $row === null.
However, I will take this opportunity to point out that concatenating variables into a SQL query string leaves you wide open to a serious security concern called SQL Injection. As the code is currently set up, users of the form will be able to run any query they like on your database which is absolutely not what you want. I recommend reading up on prepared statements to mitigate this problem.
I am creating a sign up page.
My code was working perfectly before on an intranet, but now, 5 years later I must use MySQL i.
What happens is I connect to the database using external PHP file, dblogin.php
<?php
$connection = mysqli_connect('mywebhost','username','password','db');
?>
That bit works fine, as the login system works using this.
Then comes my registration system.
It has been a while since I coded in PHP, mostly working using Wordpress now.
<?php
include 'dblogin.php';
if(isset($_GET['i'])){
if($_GET['i'] == '1'){ //if we want to insert a new user
$tblName="tblUsers";
//Form Values into store
$FirstName=$_POST['firstnamecreate'];
$Surname=$_POST['Surnamecreate'];
$Username=$_POST['UsernameCreate'];
$UserType="stu"; //never mind this, it just seperates admins from standard users
$Email=$_POST['EmailCreate'];
$Password=$_POST['PasswordCreate'];
$ExistingUserVerification = mysqli_query ($connection,"SELECT COUNT(*) as num FROM tblUsers WHERE UserName = $Username");
$UserResults = mysqli_query($connection,$ExistingUserVerification);
if($UserResults[0] == 1){
$CreatedStatus = "$Username already exists in the user database. Please choose a different Username.";
}else{
$sql="INSERT INTO $tblName(UserName, Password, UserType, FirstName, Surname, EmailAddress)VALUES('$Username', '$Password', '$UserType', '$FirstName', '$Surname', '$Email')";
$result=mysqli_query($connection,$sql);
if($result){
$CreatedStatus = "$FirstName, you have registered successfully. Click " . "<a href=Login.php>". "HERE". "</a>" . " to login. " . "<br />"."Please note: Hacking of this site is not permitted.";
}
else {
$CreatedStatus = "Unfortunately $Username was not created successfully. Please check your entry or check whether the user already exists.";
}
}
}
}
?>
The problem i am getting is around the
$ExistingUserVerification = mysqli_query ($connection,"SELECT COUNT(*) as num FROM tblUsers WHERE UserName = $Username");
$UserResults = mysqli_query($connection,$ExistingUserVerification);
part.
I have tried all sorts. With the current format, it results in:
Warning: mysqli_query(): Empty query in /home/trainman/public_html/Register.php on line 26
removing $connection results in it expecting 2 parameters and removing i says depricated.
Any help much appriciated. It has been a while since I last used php so sorry if the code is untidy. The select COUNT (*) checks if there is another user with the same username, if there isnt it will submit form values to the DB
This error is coming from the extremely simple fact that you are sending an empty query to mysqli. The query is empty. It's but an empty string. Nothing.
So just check your variables.
The second parameter to mysqli_query() should be a PHP string contains a legitimate SQL query. Anything else will cause an error.
I'm trying to check for an existing entry in MySQL before executing the INSERT statement. If the user enters a name already in the database (field is set to unique) then they should be prompted to re-enter the name.
The problem I'm having is that if the new entry matches a record in any form then the error message displays and no INSERT happens.
For example, if the user enters DUMMY_NEW and there is a record DUMMY_OLD they aren't able to add the record even though DUMMY_NEW does not exist in the table.
I've searched and tried other answers already but can't seem to get this to work.
Code with extraneous bits removed for clarity:
//Create connection to database using mysqli
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
//Set variables according to user input on previous form
$Server_Name = $_POST['Server_Name'];
//Check for duplicate server name - if exists inform user else run INSERT ($stmt)
$checkdup = "SELECT * FROM dcr_table WHERE SERVER_NAME = '".$Server_Name."'";
$dupresult = $conn->query($checkdup);
if($dupresult = 1)
{
print "<br>Error! <p></p>";
echo "" . $Server_Name . " already exists in the DCR";
print "<p></p>Please check the Server Name and try again";
}
else {
//Define the INSERT statement
$stmt = "INSERT INTO dcr_master (Server_Name, Description,..., ... , ... )";
//Execute the INSERT statement
$conn->query($stmt);
//Success and return new id
echo "<br><p></p>Record Added!<p></p>";
echo "New id: " . mysqli_insert_id($conn);
//Drop the connection
$conn->close();
};
Edit:
I'm aware of the injection vulnerability. The MySQL account only has SELECT, INSERT and UPDATE rights to the table. The end user must supply the password or submit will fail. This is small app with limited user access at the moment. MySQL escape strings will be implemented after current issue is resolved.
Edit 2:
Using Hobo Sapiens method does work in reporting an existing entry however a new (empty) row is still added to the table. The record ID still auto-increments so what I get is id#300 - record, id#301 - blank, id#302 - record. Is this a result of the IGNORE in the INSERT statement?
Your code creates a race condition if two people attempt to create the same ame at the same time and you're not handling the fallout properly.
If you have set the SERVER_NAME column to UNIQUE then you needn't check for the existence of a server name before you perform your INSERT as MySQL will do that for you. Use INSERT IGNORE ad check the number of affected rows after the query has executed to find out if it worked:
//Create connection to database using mysqli
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
//Set variables according to user input on previous form
$Server_Name = $_POST['Server_Name'];
//Define the INSERT statement with IGNORE keyword
$stmt = "INSERT IGNORE INTO dcr_master (Server_Name, Description,..., ... , ... )";
if ($conn->query($stmt) === false) {
die("Database error:".$conn->error);
}
// Check for success
if ($conn->affected_rows == 0) {
print "<br>Error! <p></p>";
echo "" . $Server_Name . " already exists in the DCR";
print "<p></p>Please check the Server Name and try again";
} else {
//Success and return new id
echo "<br><p></p>Record Added!<p></p>";
echo "New id: " . $conn->insert_id;
}
This is an atomic operation so no race condition, and it involves only one call to the database.
I recommend you use either the OOP style or the procedural style for mysqli_*() but don't mix them. Usual warnings about SQL injection apply.
Use mysqli_num_rows
$row_cnt = $dupresult->num_rows;
if ($row_cnt > 0) {
echo "There is a matching record";
}else {
//insert into table
}
This statement:
if($dupresult = 1)
will always return 1. You should first retrieve the first query result (if any), like so:
$row=$dupresult->fetch_array(MYSQLI_NUM);
and then compare the result against NULL:
if(!$row)
This question already has answers here:
How to validate an Email in PHP?
(7 answers)
Closed 9 years ago.
I have a newsletter subscribe form on my website and i want it to go to a page that
confirms the user has been signed up. At the moment it just refreshes the page and gives
you a little message where the form box was. Having tested it, it also doesn't care whether
you put the email address in wrongly etc. I would like it so it checks this info and only
submits correct email addresses. The code that is there at the moment is
<?php
// get vars
$email_address = strtolower(trim($_REQUEST['email_address']));
if((strlen($email_address) > 0) && (strpos($email_address, "#")))
{
// add to db
$newsletterQry = db_query("SELECT * FROM newsletter_subscribers WHERE email='" . mysql_real_escape_string($email_address) . "'");
if(db_num_rows($newsletterQry) == 0)
{
// add
db_query("INSERT INTO newsletter_subscribers (email, created) VALUES ('" . mysql_real_escape_string($email_address) . "', NOW())");
}
}
// return back to the index page with confirmation
header("location: ".$_SERVER["HTTP_REFERER"]."?nlMsg=".urlencode("You've been added to the site newsletter."));
exit;
?>
See the solution on How to validate an Email in PHP.
You want to sanitize e-mail addresses using either RegEx, or PHP's built-in filter_var() function.
<?php
$email_address = strtolower(trim($_REQUEST['email_address']));
if (filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
// This email address is valid insert into newsletter
}