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)
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')");
}
Ok, I'm confused. I have some code that searches a database table for a username, and then uses an if else statement to run some code depending on if the user is found or not. My code is below. The problem is that the code isn't even seeing the if else statement, and I have no idea why. Any help is appreciated.
$sqluser = "select * from users where username='" . $user ."'"; //Searching to see if the user is in the database
echo $sqluser . "<br><br>"; //writes out the select statement to make sure it is correct
$query = mssql_query($sqluser); //returns the results
$num_rows = mssql_num_rows($query); //gets the number of rows returned
echo $num_rows; //writes out the number of rows
if ($num_rows==0) //determines what happens next if the user exists or not
{
//displays an error box if the user doesn't exist
echo "<script type=text/javascript>";
echo "alert('That user doesn't exist. Please try again.')";
echo "</script>";
}
else
{
//will be code to run if the user does exist
echo "<script type=text/javascript>alert('Testing.')</script>";
}
I couldn't add a comment. So I will write this as an answer instead.
Since you state that the alert JavaScript is showing in the page source, this mean that the IF/ELSE statement in PHP is working fine. The problem is with the single quote. You have a single quote inside a single quoted alert function. Hence the JavaScript alert function cannot be executed.
echo "alert('That user doesn't exist. Please try again.')";
Try using this instead
echo "alert('That user doesn\'t exist. Please try again.');";
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.
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.';
}
}
I have a PHP form that enters data into my MySQL database. My primary key is one of the user-entered values. When the user enters a value that already exists in the table, the MySQL error "Duplicate entry 'entered value' for key 1" is returned.
Instead of that error, I would like to alert the user that they need to enter a different value. Just an echoed message or something.
How to turn a specific MySQL error into a PHP message?
To check for this specific error, you need to find the error code. It is 1062 for duplicate key. Then use the result from errno() to compare with:
mysqli_query('INSERT INTO ...');
if (mysqli_errno() == 1062) {
print 'no way!';
}
A note on programming style
You should always seek to avoid the use of magic numbers (I know, I was the one to introduce it in this answer). Instead, you could assign the known error code (1062) to a constant (e.g. MYSQLI_CODE_DUPLICATE_KEY). This will make your code easier to maintain as the condition in the if statement is still readable in a few months when the meaning of 1062 has faded from memory :)
You can check the return value from mysql_query when you do the insert.
$result = mysql_query("INSERT INTO mytable VALUES ('dupe')");
if (!$result) {
echo "Enter a different value";
} else {
echo "Save successful.";
}
try this code to handle duplicate entries and show echo message:
$query = "INSERT INTO ".$table_name." ".$insertdata;
if(mysqli_query($conn,$query)){
echo "data inserted into DB<br>";
}else{
if(mysqli_errno($conn) == 1062)
echo "duplicate entry no need to insert into DB<br>";
else
echo "db insertion error:".$query."<br>";
}//else end
With mysql_error() function
http://php.net/manual/en/function.mysql-error.php
Use mysql_errno() function, it returns the error numbers. The error number for duplicate keys is 1062.
for example
$query = mysql_query("INSERT INTO table_name SET ...);
if (mysql_errno() == 1062){
echo 'Duplicate key';
}
This is my full code that I used and works perfect. Its PDO friendly, and can handle your error easily, (once you have used die to discover what that is. Then you can copy the error message from there, and enclose it in an if. This came from a signup page, where I wanted to redirect to the login page, if the primary key (email) was found, and produced an error.
function insertUserDetails($email, $conn){
try {
$query = $conn->prepare ("INSERT INTO users (emailaddress) VALUES (:email)");
$query ->bindValue('email', $email);
$query->execute();
}
catch (PDOException $e) {
if(str_contains($e, '1062 Duplicate entry')) {
header("Location: login.php");
}
die("Error inserting user details into database: " . $e->getMessage());
}
}