php - mysql: store a DEFAULT value as a variable

772

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?

378

Answer

Solution:

You don't. You uselast_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 thatlast_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.

600

Answer

Solution:

MySQL: You can find this in MySQL by using theLAST_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');

People are also looking for solutions to the problem: javascript - PayPal Donation Confirmation on my web-page

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.