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.
Related
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.
How can I insert more than one row for the same value
for example, each user has to submit 2 forms so the username is the same in each form but the information is different
I tried to use UPDATE but it removes the ole information and replaces it with the new one while I want to keep both
is there a way to do that?
insert into your_table (username, col2)
values ('user1', 1),
('user1', 2)
Have two tables, 'USERS' and 'FORMSUBMISSIONS'
When a user submits a form for the first time, a new entry is created in the USERS table, which is unique for each user, and would contain information connected to the user.
And whenever a form is submitted (including the first time), an entry is written to the FORMSUBMISSIONS table with the details of that submission, and a foreign key back to USERS.
That's a cleaner data model for this situation. It will also help future queries on the data. If you are limited to a single table for some reason, then successive inserts will work as above, as long as there is no unique key on the USER field.
you can add duplicate data just your primary key can't be duplicated because it causes primary key constraint. so what you can do is have an extra column let's say "ID" make it your primary key. While submitting the row keep on adding ID column's value by one, rest of the data could be same.
It depends on whether your USERNAME column allows duplicates.
If it's the primary key of the table, your table schema doesn't support what you want to do, because PK should be UNIQUE.
If your USERNAME column allows duplicates, you can use INSERT:
declare #username varchar(max) = 'your_username' --declare a variable to use the same username
insert into table_name (username, form_data)
values(#username, 'form_data_1')
,(#username, 'form_data_2')
It also depends on how you're executing the SQL statement. I would definately go and create stored procedure to do this insert.
you can use bulk insert query for that. as suggested by #huergen but make sure that your username or any field that might be in form data does not have UNIQUE key index. you can also add another field that works like PRIMARY key in that table.so many ways to do but it depends upon your requirement.
Use below insert format to get your desired result:
insert into Table_name(Field1, Field2)
SELECT 'user_1', 1 UNION ALL
SELECT 'user_1', 2
I am building the request new password functionality and for the purpose I have created a separate table called users_forgotpasscodes which consists of 3 fields user_id, code and requested. Codes will be sent to users' emails and will be valid 1 day. I decided to go with a separate table instead of creating an extra column in my users table because I suppose a very little amount of users will be using this function so it makes no sense to have all users have an attribute that they will probably not use.
Anyway what I stumbled upon is when the user goes to the "forgot my password" page and enters his email address this is what happens
self::$db->prepare("INSERT INTO users_forgotpasscodes (id, code, requested) VALUES ((SELECT id FROM users WHERE email = ?), '{$code}', NOW())")->execute([$data['email']])
The problem is that I further down in this code I need the user's ID in order to be able to navigate them accurately from their inbox to the correct page to create a new password.
My question is can I retrieve the entire row that I have inserted without making another select query?
The tricky part is that I can't use lastInsertId() because column id in the codes table is not primary key it is just an ordinary index because one user can send multiple requests of this nature and I want to be able to keep track of them.
Not absolutely sure but from your comment, it looks like you just want to return the ID column (which is not a auto_increment field) of the last inserted row.
In that case, have the INSERT operation through a stored procedure and use a OUTPUT parameter to get the inserted ID value. Then you can use the same anywhere in your application code. A sample code below
DELIMITER $$
CREATE PROCEDURE sp_Insert(
IN col1 VARCHAR(25),
IN col2 VARCHAR(10),
IN email VARCHAR(30),
OUT ret_ID INT)
BEGIN
INSERT INTO your_table(ID,col1,col2) VALUES(ID,col1,col2);
SELECT ID INTO ret_ID FROM your_table where Email = email; <-- assign here
END$$
DELIMITER ;
Then call your procedure from application code and fetch the ret_ID
CALL sp_Insert(1, 'blah', 'blah blah', #ret);
SELECT #ret;
I need a table where to keep imported contacts (emails) by users, something like an address book.
Now the table look like this: imported_contacts: id, user_id, email, etc....
I'm thinking to create a table imported_contacts: id, email, etc and another table user_contacts: id, user_id, imported_contact_id, date, etc to avoid keeping duplicate emails in table imported_contacts. So with the new idea I keep in imported_contacts all imported email in the other table user_contacts I keep relationship between users and imported_contacts.
Is this a useful idea?
If I understand this correctly, if two users add the same contact, it is stored on just one row in the table, and both the users see the same row.
I see two problems with this:
if one user updates the email (or any other information of the contact), the information will also appear updated to the second user, and the initial information of the second user would be lost.
I don't know if you store other fields besides email, but if you do, you must consider that they might have different values, depending on the user; for example, if you store the name of the contact, the first user might write the contact's full name, and the second user, the high-school nickname.
Now it really depends on what this application is used for. If it's just for the internal use of one company, their client database for example, then it might be useful to have any changes propagate to all the users, so problem no. 1 would not really be a problem. But otherwise it wouldn't be ok.
I am building a service which provides a newsletter system for the users.
My question is, how to organize it on the database? user opens account -> there is a news row on the data base -> how the email will be stored? I thought about something like:
user#mail.com,HASHCODE|user2#anothermail.com,HASHCODE|someone#mail.com,HASHCODE ..
(that will be stored on one field of the user's row, HASHCODE for remove the email)
Then using explode() to order it in an array. but I don't know if it's the best way to order the mails.. what do you think?
Why don't you store emails in separate table UserEmails and make a relationship with user table. For starting point you may look at this link
Useremail table will have three fields UseremailID email UserID
UseremailID email UserID
1 sss#ss.com 1
2 asasf#ssf.com 1
I would recommend you to read some relational database so that you get some idea about tables and relationships
You should consider using a table structure like this:
Table 'subscription'
id int(20) PK auto_increment
email varchar(100) UNIQUE index
This will cause you having to insert a new row into the table with a ID and a e-mailaddress (which will both be unique so you dont get double records)
I would create a table to store the newsletters and another one to create the relation between users and newsletters so you'll have a better control over your information.
Three tables: User, User_Newsletter, Newsletter
The User_Newsletter will only store the user_id and newsletter_id
Database services don't seem to be so flexible (even though they were introduced to be). Normal UNIX filesystem hierarchy and plaintext files are the best way to store information. You don't know the internal structure of a database. But you know everything about your filesystem, including the file permissions and encryption
For example, take Croud Mail, a free e-mail newsletter service from me. I don't use databases, but it the coding is very flexible and safe.