Saint Robson
Saint Robson

Reputation: 5525

PHP Getting Previous MySQL Query's ID For Next Queries, How?

I have a simple question about MySQL and PHP here. Let's say I have this PHP syntax :

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin',35)");

on that Person table, there's a column named ID (Auto Increment). how to get Peter Griffin's ID after INSERT process is done without making another SELECT query?

or is it possible to do INSERT for 2 tables using single query? for example I want to INSERT Peter's address as well on Address table :

mysql_query("INSERT INTO Address (City, State, Zip)
VALUES ('Cupertino', 'California', 35212)");

that's all..

Upvotes: 1

Views: 213

Answers (1)

David
David

Reputation: 3821

$new_id = mysql_insert_id();

Put that right after your INSERT query and it will give you the id.

I would't recommend trying to do two INSERTs in one, and the mysql_insert_id() method will make it simplest for you and your code.

Upvotes: 4

Related Questions