Link to home
Start Free TrialLog in
Avatar of bcops
bcops

asked on

Insertion Query into MySQL

Hi,
Wonder if anyone can help.

I have a table I'd like to insert a row into using PHP. This table will be being used by a CMS, so at any point any no. of users could be inserting rows into it.

Once the code has done the insert, I'd like to get the recordID of the new row.
So I could: do a select on the table immediately following the insert to get the new recordID.

I can't 100% rely upon any auto-increment feature since someone else could have inserted a new row in between my inserting, then finding the new recordID using auto-increment.

Is there anything very handy in PHP like:

newRecordID = php_insert_row (insert parameters ....)

that returns the new record ID for me without relying upon auto incremenet and one that would mean I wouldn't have to write a cumbersome select query immediately post the insert?

This is PHP4 running wtih MySQL 3.x.

Thanks for any help,
Ben.











ASKER CERTIFIED SOLUTION
Avatar of hernst42
hernst42
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nesnemis
nesnemis

Hi bcops,

to get the id use:
    $id = mysql_insert_id($sqlInsertStatement);

nesnemis
From the MYSQL documentation pages:
http://dev.mysql.com/doc/mysql/en/Getting_unique_ID.html
--------
When a new AUTO_INCREMENT value has been generated, you can also obtain it by executing a SELECT LAST_INSERT_ID() statement mysql_query() and retrieving the value from the result set returned by the statement.

For LAST_INSERT_ID(), the most recently generated ID is maintained in the server on a per-connection basis. It will not be changed by another client. It will not even be changed if you update another AUTO_INCREMENT column with a non-magic value (that is, a value that is not NULL and not 0).
--------

So, follow your INSERT SQL statement with a "SELECT LAST_INSERT_ID()" and you'll be fine

_Blue