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;
Related
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
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.
I am currently creating a database for a sort of game/reviewer based application. Whenever a user submits a review of a restaurant or such it adds points to his score. A summary of the SQL script would be:
CREATE TABLE user
userid CHAR(30)
user_name....
userpoints largeint
etc.
The table for the reviews is here:
Restaurantid largeint (auto incrementing)
restaurantname CHAR(30)
etc.
How do I program the app to give the points whenever a review is posted?
Use a trigger that gets fired automatically on every insert in the reviews table:
delimiter |
CREATE TRIGGER review_trigger AFTER INSERT ON `reviews`
FOR EACH ROW BEGIN
update user
set userpoints = userpoints + 1
where userid = NEW.reviewer;
END
|
delimiter ;
I assumed you have a column in your reviews table that relates to the user - I called it reviewer.
You can either create a Trigger on the Review table that will insert into user, or create a Procedure to handle both inserts which then gets called by your application.
You are going to want to do a bit of research into triggers. Triggers allow you to run SQL statements when records are selected, updated, inserted etc.
http://dev.mysql.com/doc/refman/5.0/en/triggers.html
You could create one of these triggers to run on insert into the review restaurant table, and have it update the users table to add 1 to the userpoints row for that user.
you can do it using triggers if you want the database to handle the problem or you would program it in php by using an insert query or update query.
I am building a simple event registration system using MySQL and PHP. I have four tables:
events: event_id, event_name
instance: instance_id, event_id, date
attendee: attendee_id, attendee_name, attendee_email, attendee_tel
registration: reg_id, attendee_id, instance_id
To clarify, the instance table contains instances of a given event, ie a specific event on a specific date.
When an attendee registers (via a form), I want to write their details to the attendee table, then write the event they have registered for in the registration table, along with the relevant attendee_id, so that when I query the registration table later on, it will show me what event has been registered for and by whom.
However, I'm new to SQL (and databases in general, not to mention PHP as well), so I'm not sure how I can do that given that the attendee_id has only just been generated by adding the attendee to the table. I can easily insert a row into the attendee table with:
$q = "INSERT INTO attendee (attendee_name, attendee_email, attendee_tel)
VALUES ( '$fullname', '$email', '$tel' )";
With the values obviously being grabbed by $_POST from the form. The form also grabs the instance_id, incidentally.
So I just need to know how I can insert the relevant information into the registration table. Any ideas?
After inserting the data to the 1st table (attendee), use the php function mysql_insert_id() to get the last auto increment id.
Then run another query to insert the data to the 2nd table (registration).
In such cases, in order to avoid any data mismatch with the two tables, its better to use BEGIN and COMMIT. So that if any MySQL error occurs in between 2nd query, it will automatically role back.
make these column in tables primary key and auto increment
events: event_id
instance: instance_id
attendee: attendee_id
registration: reg_id
and you can get the last inserted id when you run query to insert in these table by following code immediate after the insert query
$id = mysql_insert_id();
use this appropriately
see mysql_insert_id()
The mysql_insert_id() function returns the AUTO_INCREMENT ID generated from the previous INSERT operation.
If you are using mysql_query() for inserting the data into the attendee table, write the mysql_insert_id() in the next line, it will gives you the recently generated attendee_id, store it in a variable and using this variable insert again in the registration table. Something like that:
$q = "INSERT INTO attendee (attendee_name, attendee_email, attendee_tel) VALUES ( '$fullname', '$email', '$tel' )";
$rc=mysql_query($q);
$a_id=mysql_insert_id();
now insert again in 'registration' table with $a_id;
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