Check if record already exists in database [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
insert contacts into database but does not want to duplicate already existing contact
Hello. I'm trying to check if an email already exists before I insert a duplicate.
So I need to check the database for the presence of the email address and if it exists ouput a message saying it already exists. Otherwise I want to insert the record into the database.
Here is the code I use to insert the email now, but I'm not sure how to check the database for existence.
$addEmailQuery = sprintf("INSERT INTO `subscribe`(`Email`) VALUES('%s')",
mysql_real_escape_string($_POST['inputEmail']));
$addEmailResult = mysql_query($addEmailQuery);
if($addEmailResult){
echo 'Email successfully submitted';
} else{
echo 'Sorry, we could not submit your email. Please try again.';
}
Anyone know how I would do this?

Do a SELECT before your Insert and check if a value is returned for this email.
Thats the simplest way to do it.
$CheckEmailQuery = sprintf("SELECT `Email` FROM `subscribe` WHERE `Email` = '%s'",
mysql_real_escape_string($_POST['inputEmail']));
$CheckEmailResult = mysql_query($CheckEmailQuery);
if($CheckEmailResult){
// Do What you are doing above
}
I have just given the idea but not tested it.

EDITED:
The initial answer will pose problems in a multi-user environment.
You should do like
INSERT ... ON DUPLICATE KEY UPDATE
Follow this answer to get it correct.
ORIGINAL POST:
if(mysql_num_rows(mysql_query("SELECT * FROM subscribe WHERE Email = '".mysql_real_escape_string($_POST['inputEmail'])."'")))
{
echo "already submitted";
}
else
{
$addEmailQuery = sprintf("INSERT INTO `subscribe`(`Email`) VALUES('%s')",
mysql_real_escape_string($_POST['inputEmail']));
$addEmailResult = mysql_query($addEmailQuery);
if($addEmailResult)
{
echo 'Email successfully submitted';
}
else
{
echo 'Sorry, we could not submit your email. Please try again.';
}
}

Related

Data inserted into the database even though it already exists

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')");
}

Android PHP Query returns user exists despite not being true

Can someone help me check why my query keeps returning the user exists despite me entering a whole set of new data? The code should be correct? I have been testing this code for awhile and I can't see where its gone wrong.
The request is sent from the app and then it takes the data via post. However something is preventing me from inserting a new row.
$checkuserexistsquery = "SELECT email, phone FROM users WHERE email='$email' OR phone='$phone'";
$insertuserquery = "INSERT INTO users (firstname,lastname,dateofbirth,phone,email,password) VALUES ('$firstname','$lastname','$dateofbirth','$phone','$email','$password')";
$checkuserexistsresults = mysqli_query($conn,$checkuserexistsquery);
if($checkuserexistsresults===FALSE){
echo "Check user query failed";
}else{
$countcheckuserexistsresults = mysqli_num_rows($checkuserexistsresults);
if($countcheckuserexistsresults>0){
//user already exists
echo "User already exists";
}else{
//user doesn't exist
$insertuserresults = mysqli_query($conn,$insertuserquery);
if($insertuserresults===FALSE){
echo "Insert user query failed";
}else{
echo "Insert successful";
}
}
}
mysqli_close($conn);
From the comments, i think you should confirm if $email and $phone should be the correct one that you want. You can echo or var_dump them before concat it to $checkuserexistsquery. I presume that maybe you assign the values, email: test#test.com or phone: 12345 somewhere else in your code, because i don't see any logical error from your code.

Avoiding Duplicates in MySQL

So I've a subscription system and I don't want a user to be able to subscribe twice with the same email.
What came into my mind is using PHP without any DUPLICATE MySQL stuffs, so I thought I can just do:
$checkvar = mysql_query("SELECT email FROM subscribers_list WHERE email = '" . $email . "'");
if (empty($checkvar)){
echo "There is no duplicate.";
}else {
echo "Duplicate found!";
}
But for some unknown reason the above code won't work as expected.
mysql_query returns a result not array or any data variable so use....
if (!(mysql_num_rows($checkvar))>0) { echo "There is no duplicate."; }
else { echo "Duplicate found!"; }
and try to format your code!
Add a MySQL constraint.
It wont allow any code to insert the same email twice.
ALTER TABLE subscribers_list ADD CONSTRAINT unique_email UNIQUE (email)

Checking if e-mail address is already used

I'm coding a registration system on php. I'm trying to make it impossible to create two accounts with same e-mail address. I wrote a code which should check it, but it doesn't work. I can create as many accounts as I want with the same e-mail. What's wrong with it?
$sqlemail = "SELECT count(*) FROM 'users' WHERE email = ?";
$result = $connection->prepare($sqlemail);
$result->execute($email);
$emailused = $result->fetch();
if ($emailused!=false) {
echo 'An account with this e-mail address already exists!';
}
Make the email field a unique key for the table. Then, if you try to insert a duplicate, mysql will throw an error.
You can then handle the error, and display your friendlier message. You can check for the error with $result->errorCode().
This also keeps you from having to make a SELECT before an INSERT.
Can you try this, use backticks in users not '
$sqlemail = "SELECT count(*) FROM `users` WHERE email = ?";
if ($emailused>0) {
echo 'An account with this e-mail address already exists!';
}
Even if the email came back with multiple results, the script will execute because you are not killing the script! You need to use exit; or die() to stop them from progressing, or a re-direct or something.
if ($emailused>0) {
echo 'An account with this e-mail address already exists!';
exit;
}

Form should show alert if duplicate username

ive created a form and im using php to check if the username exists in the database, if it is then the form will not submit and echo an alter that the username has already been taken, if i fill the form out and submit it with a name thatn i know is in the database, i get the error saying that the username already exists, but i also get the text that says.. Thank you for signing up
basically its showing the error correctly but it still submitting all the for data to the database
can you see anything in my code thats causing this??
//Check to see if the username is already taken
$query = "SELECT * FROM clients";
$result = mysql_query($query) or die(mysql_error()); // Get an array with the clients
while($row = mysql_fetch_array($result)){ // For each instance, check the username
if($row["username"] == $username){
$usernametaken = true;
}else{$usernametaken = false;}
}
// If the username is invalid, tell the user.
// Or else if the password is invalid, tell the user.
// Or else if the email or PayPal address is invalid, tell the user.
// Else, if everything is ok, insert the data into the database and tell
// the user they’ve successfully signed up.
if($usernametaken)
{
echo "That username has been taken.";
}
if(!preg_match('/^[a-zA-Z0-9]+$/', $username ))// If our username is invalid
{
echo "The username can only contain letters or numbers"; // Tell the user
}
else if(!preg_match('/^[a-zA_Z0-9]+$/', $password ))// If our password is invalid
{
echo "The password can only contain letters or numbers"; // Tell the user
}
// If our email or PayPal addresses are invalid
else if(!preg_match("/^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/", $email))
{
return "The email or PayPal address you entered is invalid."; // Tell the user
}
else{
// Inserts the data into the database
$result = mysql_query("INSERT INTO clients (client_ID, username, password, email, paypal)"."VALUES ('', '$username', '$pw', '$email', '$paypal')");
echo "Thank you for signing up.";
}
?>
You need to break out of your function if the username is no good. You could add an else if before the preg match if you don't want your last line to run. Basically your program flow is
//if username taken
//if bunch of cases
//else add client
There is nothing separating your two if statements.
Your SQL statement is a bear too. You are looping through every client in your db to see if it is a duplicate. Just add a where statement
$query = "SELECT * FROM clients WHERE clientName = '$clientName'";
You don't have anything to tell the script to stop executing if it finds that the username is taken. Restructure your if-else statement like this:
if($usernametaken)
{
echo "That username has been taken.";
} else {
// If username is not taken...
}
Instead of using several else ifs may I recommend using exceptions for this situation.
Demonstration:
<?php
try
{
if ($usernametaken) throw new Exception('That username has been taken.');
// If we've reached here we know data has been checked properly
$result = mysql_query("INSERT INTO clients (client_ID, username, password, email, paypal)"."VALUES ('', '$username', '$pw', '$email', '$paypal')");
echo "Thank you for signing up.";
}
catch (Exception $e)
{
echo $e->getMessage();
}
?>

Categories