Heres the scenario:
I am supposed to make a small site where user can register, I am using a table named users with fields
userid int unsigned auto_increment,
name varchar(50),
gender enum('m','f'),
time datetime,
joiningyear int unsigned,
primary key (userid)
When I insert a new user I am also supposed to log him in by saving an encrypted form of his userid as a cookie. The problem is this, if userid is already used, it is auto incremented by 1, as is obvious. I would like to recieve this new value as an output of my insert query, without adding another query that fetches it, this will makes things easy.
Currently I am using two seperate queries one checking if randomly chosen userid is already taken and second inserting the entry.
Insert into users(......) values(...)
Is there a way to achieve this with one query?
Depending on your MySql adapter you can use:
mysqli_insert_idorPDO::lastInsertId. There is alsomysql_insert_idbut described with:If you are using any framework, it should support returning last inserted id.