Do not insert data if Email already exist PHP - php

I am trying to create a web application for user to use their email and search for the table number and insert the Email in mysql table. If the email already in the table, I dont want it to be insert one more time. Below is the code I added in my php file.
INSERT INTO employee (phone_number)
VALUES ('$search')
I have tried the ON DUPLICATE KEY UPDATE as well and it is not working. Below is the code I used in my php file.
INSERT INTO employee (phone_number)
VALUES ('$search') ON DUPLICATE KEY UPDATE phone_number = '$search'

Thanks for the people that help me in the comment area. I manage to figure it out with the help. You will need to set the email to unique in the database to use the ON DUPLICATE KEY.
Also got found some articles on the internet talking about SQL Injection and knowing that using proper name for columns is very important. Thanks for the help from everyone in the comment area again.

Related

insert in delete values in mysql column

New to MySQL, I have user table that holds data when users signup. At sign up 1 email is required but I want them to be able to add additional emails to the mail col of the User table. Is this possible? I have tried:
INSERT INTO users (email) VALUES ('email#fake.com') WHERE user_id = 1;
and found out INSERT won't respect 'WHERE'. First is this even the correct approach? If not, how can add multiple values and be able to delete a one of multiple values later if the user chooses to?
First of all, your simple solution is using CONCAT
UPDATE `users`
SET `email` = CONCAT(`email`, ',', 'new_email#mail.com')
WHERE id = 1
But! Here comes the problem, when your user wants to delete an email.
You'll have to explode your current email string, remove value from it, and do an update like:
UPDATE `users`
SET `email` = 'string of emails'
WHERE id = 1
That's why storing emails should be either in separate fields, like email1, email2 if you have 2 emails only.
If you allow users to have a lot of emails - then you should add a new table, called user_emails, for example, with scheme like:
user_id | email
Then selecting emails become something like:
SELECT `email` FROM `user_emails` WHERE `user_id` = 1
Adding email is just another insert:
INSERT INTO `user_emails` VALUES (1, 'new_email')
And removing is:
DELETE FROM `user_emails` WHERE id = 1 AND email = 'new_email'
Mysql is a relational db language, and as such promotes relating tables for times like these. As #Fabio commented, your simplest approach would be to have another table of email address, and replace your email column on users with an userEmailId column that allows you to relate multiple rows in this email table back to this user by having each row in email contain this userEmailIdand the actual email data.
Adding a table is the simplest approach and the only other way I can think of achieving this is by adding more columns to user for additional emails. You could then use update on a user you want to add an email to by updating a null email column.
A third approach, which may work depending on how you're using these queries and if it's part of larger php, node, or the like application, would be to append a new email to a current email and separate the two with some sort of character not allowed in an email, a space character could be a simple example. Within your server language you can separate this string into your individual emails. Using update can achieve this, but you will have to subquery to carry over current data within the email field upon adding a new email.

Check if data entered by user in html form already exists in database in php

After entering data in html form while clicking on button to add the data in the database, I want to check whether the user already exists in the database. I am using php v5.3.5 and mysql v5.5.8.
Data is stored in 2 tables simultaneously named person and other and there is no primary key(in both columns) since there is no column which can be treated as primary key
Can any one help me how to do that??
Code is::
$sqlComm="Insert into person(Name,father_name,date_birth,
gender,Res_Address,Mobile_no)
values('$name','$fatherName','$dob',
'$gender1','$resAddress','$mobileNo')";
$sql="insert into other_staff(p_id,employer,off_ph_no)
values('$pId','$employer1','$phOffice')";
Id is automatically generated for each person which is retrieved and stored in other table as p_id.
combination of name,father_name,date_birth,employer can be made unique..
It seems like none of the fields suggested can be a primary key, any of them or a combination of them cannot uniquely identify a person. It's a really strange database design and I urge you to check your database design.
You will have to a search by doing a separate select query to find if the user exists. Also Ensure both the statements are executed inside a transaction.
You will have to think about what makes a person unique for your schema/application. Changing the mobile number probably does not make one a new person, but am i the same as an existing person, if we share the name, father_name, date_birth and gender? If so, make that a unique key and you will have something your database can tell you, that it already exists. Just in case you did not already know: keys can span multiple columns.
Dispite with a bad schema, we can find a way(given below) to check weather a user exist or not. BUT I think you also want to check second table THAT with particular user there is an employer or not. Then here is problem in your database cause there is no column in PERSON or OTHER_STAFF's table which can tell us the Particular employer of a specific user in PERSON table
Solution: But for this condition you can use cross join to get nearly correct result:
if($result=mysql_query("SELECT 1 FROM person p CROSS JOIN other_staff e WHERE p.name='$name' AND p.father_name='$father_name' AND p.date_birth='$dob' AND p.gender='$gender1' AND p.Res_Address='$resAddress' AND p.Mobile_no='$mobileNo' AND e.employer='$employer1' AND e.off_ph_no='$phOff';")){
if(mysql_fetch_array($result)){
//exist
}else{
//not exist
}
}
Suggestion: Next time store auto generated id in PERSON and OTHER STAFF table BUT for this project- If you can store p_id in PERSON table then this query will return 1 on exist, otherwise null(same in above):
$sql="SELECT 1 FROM person p LEFT JOIN other_staff e ON p.p_id=e.p_id WHERE p.name='$name' AND p.father_name='$father_name' AND p.date_birth='$dob' AND p.gender='$gender1' AND p.Res_Address='$resAddress' AND p.Mobile_no='$mobileNo' AND e.employer='$employer1' AND e.off_ph_no='$phOff';";

Inserting data into Mysql with multiple unique keys

My MYSQL query
$db->query("INSERT INTO customers (first_name,last_name,address,city,state,zip,phone,dnc,user_id)
VALUES ('$firstname','$lastname','$address','$city','$state','$zip','$phone','$dnc','$userid') ON DUPLICATE KEY UPDATE phone=phone");
What I am doing is putting customer information into a database. I Wanted to make sure that each customer was inserted once into the database. This query works for that by using the phone numbers as a unique key. Now the problem I'm having is I want to be able to have duplicates of customers in the database, but no duplicates of customers per user.
In my application multiple users have customers that they have added, but they can't see customer's that other users have added. I want the query to NOT insert only if the user_id and the phone are already in the database. I tried adding
phone=phone AND user_id=$userid
to the end of the query but Haven't been able to get it to work right.
Any help would be appreciated, thanks.
Use this query to add UNIQUE index above both fields:
ALTER TABLE customers ADD UNIQUE `unique_customer` ( user_id , phone)

Using mysql for a mini game

I'm new to mysql and wanted to consult about using mysql for my mini game. The idea is that from a game i get two variables - one is email, and another is score.
I'm thinking of creating a table with two columns and setting email as the primary.
The question is how do I make php script replace score value for a player which tries for the second time?
For example user#user.com scores 100 in the first try, script adds that as INSERT INTO table VALUES ($email,$score); then user tries another time, same script tries to add but gets duplicate error. Any help on script logic would be great! cheers
INSERT
INTO mytable (email, score)
VALUES ($email, $score)
ON DUPLICATE KEY
UPDATE
SET score = $score
This requires email to be the PRIMARY KEY of mytable.
It's difficult to answer without more details. If there is some sort of session or pre-registering of the player, you could insert a "default score" of zero, for instance, and then always update instead of insert. If not, Queassnoi's solution is probably the best.
You need to use UPDATE rather than INSERT
UPDATE table SET score = $newScore where email=$email
You are trying to add a new record with the same primary key, hence the error message

INSERT command inserting duplicates

I am writing a quiz website.
What should happen is:
A page has a question on it and four buttons or a textbox.
When you click a button, it calls itself with
the answer number in the address
like: ?q=[question number]&a=[answer].
If the question
uses a textbox it POSTs the answer.
This code should then detect that
something has been sent to it and
write that to a database.
The user id is stored in a cookie.
There is also a key column in the database. the idea is that it stores all answers a user has submitted over time and users can change their answers.
<?PHP
mysql_connect("------", "------", "------") or die();
mysql_select_db("------") or die();
$q=$_GET['q'];
if(isset($_GET['a'])){
$a=$_GET['a'];
} else {
$a=$_POST['longanswer'];
}
if(isset($a)){
$u=$_COOKIE['id'];
if($qust['atype']==1){
mysql_query("INSERT INTO answers (`userid` ,`answer` ,`qid`) VALUES ($u, $a, $q);");
} else {
mysql_query("INSERT INTO answers (`userid` ,`answer` ,`qid`) VALUES ($u, '$a', $q);");
}
}
?>
I don't think it should matter, but later on on the code, it queries the database with the SELECT command.
When i run this code, it seems to enter 2 or 3 entries to the database. The trend seems to be that when i run the code it enters the previous answer, followed by the new answer.
Any help would be greatly appreciated. Thanks,
Logan
It seems like what you want to do is to allow only one answer per question per user. If that's the case, you'll want a UNIQUE constraint on your table on userid and qid:
ALTER TABLE answers ADD UNIQUE(userid,qid);
This will result in an error when you try to insert a row with the same userid and qid. If you want to allow users to change their error, you can change your INSERT query to:
INSERT INTO answers (userid ,answer ,qid) VALUES ($uid, '$answer', $qid) ON DUPLICATE KEY UPDATE answer='$answer'
This will prevent multiple records from showing up in the database, but multiple INSERTs might still be called from your PHP code. To fix that, we'd have to see some more of your code.
Another option would be to first try to retrieve the data you're about to enter into the database. If you find it, it's already there, so don't add it again. The suggestions for using constraints are sound but if the data you're trying to prevent duplicates of isn't easily added to the constraints or the data you don't want duplicates of is not exactly the same data (say just similar data) then this is another option.
The unique constraint mentioned by cmptrgeekken should definately be added if you only allow one answer per user, but then you must also handle the primary key violation if it occurs: Inform the user it has already replied OR replace the previous value, depending of how you want the site to work.
Also, Is for some reason the request triggered more than once? Maybe by javascript, or some other logic of yours? If duplicate answers appears when you only click once, this seems to be the case.
/B

Categories