1

I am wondering how to store the value of a primary key, auto-incremented by "DEFAULT" so that I can insert it as a value in another table row.

So far I have:

$sql = "INSERT INTO sales (
            sale_id,
            sale_amt,
            sale_date) 
        VALUES (
            DEFAULT,  # <--- how to store the resulting value of this?
            '$amt',
            '$date'
            )";

I need the specific value created by "DEFAULT" to be stored, so that I can insert it into another table's row. How do I do this with either PHP or MySQL?

1
  • i think u need foregin key rather than that Commented May 27, 2014 at 19:26

2 Answers 2

2

You don't. You use last_insert_id() to retrieve it AFTER you've performed the first insert.

INSERT INTO foo (bar) VALUES (baz)
SELECT @id := last_insert_id();
INSERT INTO other (id, parent) VALUES (null, @id)
INSERT INTO yetanother (id, parent) VALUES (null, @id)

Note that last_insert_id() is not smart and will return the id of the LAST insert you did. If you do two inserts, and then try to get the ids, you'll get the id of the second (last) insert.

Sign up to request clarification or add additional context in comments.

Comments

1

MySQL: You can find this in MySQL by using the LAST_INSERT_ID() function, as the last insert ID will be returned that you inserted for an AUTO_INCREMENT value.

$sql = "INSERT INTO sales ( sale_id, sale_amt, sale_date) VALUES ( DEFAULT, # <--- how to store the resulting value of this? '$amt', '$date' )";

sql2 = "INSERT INTO records ( sale_id, customer_name, other_info) VALUES ( LAST_INSERT_ID(), <-------- correct sales_id '$name', '$info');

2 Comments

Consider the warning on the docs for mysql_insert_id(): "This extension is deprecated as of PHP 5.5.0, and will be removed in the future.".
You're right. Removing the PHP and sticking solely to mySQL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.