How would you get an auto_increment value on an insert query? - php

So, I was wondering if you were to launch this query:
INSERT INTO users (name, gender, location) VALUES ('Ricky-Bobby', 'm', 'Daytona Beach, FL');
And suppose that users has another auto-incrementing columns for the primary key, how would you be able to get the value of that primary key without launching another query?

Codeigniter simplifies the MySQL query SELECT LAST_INSERT_ID() through the function $this->db->insert_id().
Although this is a query, it's a very light one that won't be a performance issue. One thing to have in note is this:
If you want the ID on the row you inserted; $this->db->insert_id()
If you want the auto_increment value, that is the next value that an INSERT will have as id, simply $this->db->insert_id() + 1

codeigniter makes this available with $this->db->last_insert_id()
http://ellislab.com/codeigniter/user-guide/database/helpers.html

You can combine LAST_INSERT_ID() with your query:
INSERT INTO users (name, gender, location) VALUES ('Ricky-Bobby', 'm', 'Daytona Beach, FL');
SELECT LAST_INSERT_ID();

You could use this if you are using PDO
http://php.net/manual/en/pdo.lastinsertid.php

Related

Mysql, How to read auto increment value in other fields of the same inserting row?

Hello I need to have the transaction id in the comment field of my transaction
mysql_query("INSERT INTO `transactiontb` (`tid`, `amount`, `comment`) VALUES (NULL,'$amount', CONCAT('Transaction # ',`tid`)')");
How can i do this?
Get off of mysql_* functions. Look at MySQLi or PDO.
Don't store the tid twice. Why not concat when you select it instead of storing it that way? This is not the best way.
For reference though, try LAST_INSERT_ID()+1):
INSERT INTO `transactiontb` (`tid`, `amount`, `comment`)
VALUES (NULL, '$amount', CONCAT_WS('Transaction # ', LAST_INSERT_ID()+1))
LAST_INSERT_ID() will give the ID of the previous INSERT not the one from the current INSERT so you must add 1.
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
The ID that was generated is maintained in the server on a
per-connection basis. This means that the value returned by the
function to a given client is the first AUTO_INCREMENT value generated
for most recent statement affecting an AUTO_INCREMENT column by that
client. This value cannot be affected by other clients, even if they
generate AUTO_INCREMENT values of their own. This behavior ensures
that each client can retrieve its own ID without concern for the
activity of other clients, and without the need for locks or
transactions.
Use the LAST_INSERT_ID() function.
LAST_INSERT_ID() (with no argument) returns a BIGINT (64-bit) value
representing the first automatically generated value that was set for
an AUTO_INCREMENT column by the most recently executed INSERT
statement to affect such a column.
Source: MySQL Documentation
Example:
"INSERT INTO transactiontb(tid, amount, comment) VALUES (NULL,'" . $amount . "', CONCAT_WS('#','Transaction',LAST_INSERT_ID(id+1)))"
Just saw you were also forgetting to put the separator for you CONCAT_WS function, so i fixed it in the example query.

mysql insert into two tables id from first

i need to insert some data into the table 'companies' with columns :
company_id | company_name
and at the same time (from the same form) into another table 'contact_persons' :
contact_name | company_id
where the company_id must be the value from 'companies' table where company_id is a PK and AI.
Is it possible to do that in ONE single step instead of inserting first the company_name and then reading the table 'companies' and retrieving the 'company_id' to insert it into the second table ('contact_persons')?
I'm not sure if that is possible, but it would be much more elegant and efficient...
Thanks in advance.
You can do it using LAST_INSERT_ID() to get the last auto increment id from Companies table and inserting the same in other table. something like
INSERT INTO companies (company_name) VALUES ('test');
SET #last_id_companies = LAST_INSERT_ID();
INSERT INTO contact_persons (contact_name, company_id)
VALUES ('test', #last_id_companies);
Not in a single statement, but in a single transaction, so they are both executed at the same time and rolled back.
START TRANSACTION;
--Your statements here
COMMIT;

auto increment id not inserted

I am using simple MySQL code to insert data from a form with auto_increment id, it works fine on local host but not on server.
this is the code I am using
$myvar=$_POST['var'];
//Insert data into mysql table
$sql="INSERT INTO mytable(id,myvar) VALUES ('','$myvar')";
in local host phpmyadmin data is inserted in table but on server phpmyadmin data is not inserted in table. In my localhost I am using XAMPP whereas phpmyadmin on IIS server.
What setting should I do in phpmyadmin on server so that id is automatically inserted with auto increment, I know I can use mysql_insert_id() to insert id but in lots of file i have used this type of code which I cannot change. I want the same setting as XAMPP that can take this type of code easily.
You as inserting '' into auto-increment id. just insert other fields and MySQL handles the auto-increment column.
$sql="INSERT INTO mytable(id,myvar) VALUES ('','$myvar')";
should be
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";
if still you are getting the error
first check, in the server your id column must marked as auto_increment.data type should be int.
if it is ok then
insert into mytable(myvar) values('test');
and try to use prepared statements to avoid the sql injection. Thanks.
hope this may usefull for you.
If you want the last of all the rows in the table, then this is finally the time where MAX(id) is the right answer! :) kind of.
SELECT fields FROM mytable BY id DESC LIMIT 1;
will get the last id then increment it to 1 // add this value to id in insert statement
or
if you have a autoincrement column change it to
$sql="INSERT INTO mytable(id,myvar) VALUES ('','$myvar')";
to
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";
auto increment inserts id itself so you don't need to pass it through code
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";
or you can do this
$sql="INSERT INTO mytable(id,myvar) VALUES (NULL,'$myvar')";
if you want want to manually insert id for some reason
$sql="INSERT INTO mytable(id,myvar) VALUES (10,'$myvar')";
First check your table Structure Property by applying query:
desc mytable (or) show create table mytable.
Check auto increment property been set for column id.
If yes means don't need to pass id in insert query.
Just write a query as :-
$sql="INSERT INTO mytable(myvar) VALUES ('$myvar')";

MySQL insert into unless col1 and col2 are both the same then update another column

For example...
My table is setup like gameid - userid - rating
When someone submits a rating, I want it to do an insert. But, if the userid and gameid are already together...I want it to just update the rating.
But if maybe that user id is just paired up with another gameid then that's fine go ahead and make a new row.
I'm sure this is out there, I just don't really know how to word what I'm trying to do.
Create a composite UNIQUE INDEX on (gameid, userid), then use a query like:
INSERT INTO `table` (`gameid`, `userid`, `rating`)
VALUES (..., ..., ...)
ON DUPLICATE KEY UPDATE `rating` = ...
See http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html.
You're looking for MySQL's REPLACE INTO functionality. Docs are here: http://dev.mysql.com/doc/refman/5.0/en/replace.html

SQL - INSERT and catch the id auto-increment value

What is the best way to get the auto-id value in the same SQL with a SELECT?
A forum said adding this "; has Return Scope_Identity()"
in the end of the SQL works in ASP.
Is there a corresponding way in PHP?
It depends on your database server. Using MySQL, call mysql_insert_id() immediately after your insert query. Using PostgreSQL, first query "select nextval(seq)" on the sequence and include the key in your insert query.
Querying for "select max(id) + 1 from tbl" could fail if another request inserts a record simultaneously.
In postgres the best way is to do something like:
insert into foos(name) values ('my_foo') returning id;
It depends on the database engine you are using. Some DBMS, like Firebird for example, have RETURNING clause you can add to your query. For example, if you have a table named TABLE1 with autoincrement column named ID, you can use this:
insert into TABLE1(columns...) values (values...) returning ID;
And it would return the inserted ID just like a regular select statement.
In Microsoft Transact SQL you can use ##IDENTITY.
e.g.
DECLARE #Table TABLE ( col0 INT IDENTITY, col1 VARCHAR(255), col2 VARCHAR(255))
INSERT INTO #Table (col1, col2) VALUES ('Hello','World!')
SELECT ##Identity
SELECT * FROM #Table
In php: mysql_insert_id()
http://us3.php.net/mysql_insert_id
or
If you wanted to genterate the number from your mySql select query, you could use this
EDIT:
SELECT LAST_INSERT_ID(`1`) + 1 FROM table
Be very careful: Apparently select nextval(seq) does not work in high concurrency - some other connection can insert between the time when you inserted and the time when you called select nextval(seq). Always test such code in high concurrency test harnesses.
In SQL Server a insert using the select statement can have an output clause which will return the identity value and whatever other columns you might need to identify which identity goes to which record. If you are using a values clause, then use select scope_identity () immediately after the insert.

Categories