marijn marijn -4 years ago 45
MySQL Question

Get the id of the just inserted row in database

I'm want to insert the id of every item in the cart to the database and couple this invoice line to an invoice that just has been created in the same case.
at the moment if i press the button its adding a new invoice to the database and after this its adding every single product in the cart but now i need to replace the 1 in the second query with the invoice id that just has been created. How can i get this to work?

case "apply":
$curdate = date('Y-m-d');
// new invoice
$sql = "INSERT INTO invoice (user_user_id, dates) VALUES ('1', '$curdate')";
$result = mysqli_query($con, $sql);
// for each item in cart insert into invoiceline
foreach ($_SESSION["cart_item"] as $item){
$car = $item["id"];
$sql = "INSERT INTO invoice_line (car_car_id, invoice_invoice_number) VALUES ('$car', '1')";
$result = mysqli_query($con, $sql);


The invoice_id is not the primary but a foreign key, the table doenst have a primary key so i dont think i can use mysqli_insert_id?

Answer Source

You can use:

$inserted_id = mysqli_insert_id($con);

or, object oriented style:

$inserted_id = $con->insert_id;

$inserted_id will have the value of just inserted row (should be auto-increment in your table).

So, your second query will look like:

$sql = "INSERT INTO invoice_line (car_car_id, invoice_invoice_number) VALUES ('$car', '$inserted_id')";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download