php - mysql: store a DEFAULT value as a variable
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?
Answer
Solution:
You don't. You use
last_insert_id()
to retrieve it AFTER you've performed the first insert.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.Answer
Solution:
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');