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;
}
Related
I've got a website and when a user registers I want to check, if the entered email has already been used to register another account.
database: users
row: email
new email: $email_register
$result = $pdo->prepare("IF email_register = ? IN email FROM users $same = TRUE");
$result->execute(array($email_register));
$user = $result->fetch();
if($same == TRUE)
{
echo email already used;
}
else
{
#continue registration process
}
I want a way to know if the email is already in the db, and if it is, for the user to be sent back to the registration page with an error message (error code transmitted via header).
Assuming that users should not have more than one account per email, an easy approach is to make the email column a unique key (or primary key) in the users table. This prevents an email being used more than once.
Try this way
// check if email is taken already
$stmt = $pdo->prepare("SELECT email FROM users WHERE email_register = :email");
$stmt->execute([
'email_register ' => $email
]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (isset($user) && !empty($user)){
// Username already taken
echo "email already used";
}else{
//redirect to registration process
}
There is no need for IF in the SQL query. Just write simple select statement like:
Select email from users where email = 'example#example.com';
if query return and result it means the email is already in database if not then you can continue to the registration process.
if($exist)
{
return false; or you redirect to registration page whatever you want to do.
}
#continue registration process
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')");
}
Problem has been solved
I have created a form that processes the changing of user information from the admin side e.g. the admin changes a user's username and/or email. I am having trouble processing multiple queries.
For example, if the admin changes the username, the query works. If the admin changes the email address, the query works. But if the admin changes the username and email at the same time through the form then only the username changes.
Any ideas? I will submit my code but I will change variables for security reasons etc. Also, anything in capitals has been changed for security reasons. The code is all correct for each individual function because as I said, if I ONLY change the email, it works and actually changes. But if I change the username AND email, only the username will change despite the fact the email query runs and it echo's the email has been changed!
Also, it is worth noting that all of the fields e.g. username field and email field are part of one form that submits to one page.
if (isset($_POST['SUBMIT_BUTTON_PRESSED'])) {
//Gather all inputs from the form and sanitise it.
//REMOVED FOR SECURITY REASONS.
if($USERNAME_NEW != "") {
if($USERNAME_NEW == $CURRENT_USERNAME) {
echo "You have entered the username you are already using. Please enter a different username.";
} else {
$CHECK_USERNAME = "SELECT USERNAME_ROW FROM USERS_TABLE WHERE username='$USERNAME_NEW'";
$RUN_QUERY = mysqli_query($CONNECTION INFO, $CHECK_USERNAME);
$RESULT = mysqli_num_rows($RUN_QUERY);
if($RESULT > 0) {
echo "That username already exists. You cannot use that username again. Please enter another username.";
} else {
$editing_username = true;
$USERNAME = $NEW_USERNAME; //NOT NEEDED BUT IT STILL WORKS
$THE_SQL_QUERY = "UPDATE USER_TABLE SET username='$USERNAME' WHERE username='$ORIGINAL USERNAME'";
$RUN_THIS_QUERY= mysqli_query($CONNECTION INFO, $THE_SQL_QUERY);
echo "The user's username has been changed to: ". $USERNAME;
}
}
}
if($EMAIL != "") {
if($EMAIL == $CURRENT_EMAIL) {
echo "You have entered the same email address to the one you are already using. Please enter a different email address.";
} else {
$CHECK_EMAIL = "SELECT USERS_EMAIL FROM USER_TABLE WHERE username='$USER'";
$CHECK_EMAIL_QUERY = mysqli_query($CONNECTION_INFO, $CHECK_EMAIL);
$RESULT = mysqli_num_rows($CHECK_EMAIL_QUERY);
if($RESULT > 0) {
echo "That email already exists. You cannot use that username again. Please enter another username.";
} else {
$editing_email = true;
$THE_NEW_EMAIL = $FINAL_EMAIL_THING; // AGAIN NOT NEEDED BUT STILL WORKS
$THE_SQL= "UPDATE USER_TABLE SET USER_EMAIL='$EMAIL' WHERE username='$USER' LIMIT 1"; // REMOVED THE LIMIT 1, STILL DOESN'T WORK
$RUN_THIS_QUERY = mysqli_query($CONNECTION, $THE_SQL);
if($RUN_THIS_QUERY) {
echo "The user's email has been changed."; // EVEN WHEN BOTH FIELDS ARE SUBMITTED THIS WORKS SO THE QUERY IS RUNNING BUT THE EMAIL DOESN'T CHANGE
}
}
}
}
Thanks for the help! Also, no un-witty remarks about how my question is structured etc. because I don't care to be honest. I just want this code working to be honest because I've been working on it for a while. This may be something simple or I might be using the wrong approach for this type of form submission.
Remember: THIS CODE DOES WORK WHEN I SUBMIT EACH FIELD SEPARATELY!
Its very hard to figure out as you are not producing the real code.
I think you have missed something here.
As you are using USER_NAME as key in the SQL's, make sure that you are using the updated username in the second sets of SQL (to update the email) as they are already replaced by the first SQL.
And there is no security risk while showing your codes snippets to someone else. Hide only the username/passwords or Identities. :)
I'm using this code as part of an email confirmation script. It works great, except I can't figure out a way to distinguish between when somebody has provided an invalid email address vs when they have simply refreshed the page (ie. already confirmed their account). The only think I can think of is putting a time stamp field in the users table that always gets updated, but I'm hoping there is a better way. I thought REPLACE would do the trick, but, while email is unique, it is not the primary key.
if (isset ($email, $token, $correctToken)){
$success = FALSE; //Set the $success variable so that we don't get an error when testing for it later
if ($token == $correctToken) {
$confirm = mysql_query("UPDATE users
SET conf = 'TRUE'
WHERE email = '$email'");
if (mysql_affected_rows() == 1) {
echo "Thank you! Your email address is confirmed and your account is actived.";
$success = TRUE;
}
}
if (!$success) {
echo "There was a problem with the confirmation. Try the link in your email again or contact us at Support#WiseRenters.com";
// Send email to admin to notify of error
exit;
}
}
Thanks in advance for the advice!
Billy
EDIT: The $email and $token variables are provided through $_GET or $_POST, in case that wasn't obvious.
A redirection would stop them from refreshing - but what if they click the link in their email again?
You should check if the current user is activated or not.
$sql = "SELECT id, conf FROM users WHERE email = '{$email}'";
$exec = mysql_query($sql) or die(mysql_error());
list( $id, $conf ) = mysql_fetch_row($exec);
if( $conf ) {
// Redirect them to their profile with a message saying "your account has already been activated"
header("Location: /profile?already_activated");
exit;
}
// your code
$confirm = mysql_query("UPDATE users
SET conf = 'TRUE'
WHERE id = '{$id}'");
In response to your comment:
Keep in mind this will only add an additional query for a user who has not activated yet. If they have activated then the redirect occurs and the page is still running only 1 query.
To optimize this a bit, you can select the user ID and confirmation status based on the email address. Then, if they do need to be activated, you can activate them based on user ID instead of email. Since an integer key is much faster, the combined time of the 2 queries will be about the same as the 1 query where you are updating based on a string column. I updated the code to reflect this.
Also, this page will probably not be accessed very frequently. Any optimizations from here would really be micro- and not really that helpful.
By the way I hope you are using mysql_real_escape_string on the email, and that conf is a boolean true/false not a string 'true'/'false'.
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.';
}
}