Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Return generated AUTO_INCREMENT value on INSERT

Tags:

php

mysql

Hopefully an easy one - I can't work out a robust solution.

I'm building a cart mechanism which generates a id_cart AUTO_INCREMENT Primary Key. The cart item has another table with cart product variables like size. I want to attribute the same id_cart in the size table.

CREATE TABLE
-> id_size_cart NOT NULL PRIMARY KEY AUTO_INCREMENT,
-> id_cart //THIS WILL BE THE AI value from the product cart
-> size_name

I've seen SELECT LAST_INSERT_ID().

How solid will this be to ensure it's the last inserted ID? Don't want customers getting the wrong size!

__ EDIT ___

Thank you for the input. Still, I'm having trouble. See actual code below;

//add product to cart table
$addtocart_sql = "INSERT INTO store_cart (id_cart, id_session) VALUES ('', '".$_COOKIE["PHPSESSID"]."')";
$addtocart_res = mysqli_query($dbConnect, $addtocart_sql) or die(mysqli_error($dbConnect));

$last_row_id = mysqli_query($dbConnect, "SELECT LAST_INSERT_ID()") or die(mysqli_error($dbConnect));

echo 'INSERT worked!<br/>';
echo $last_row_id;

Error shows as

Parse error: syntax error, unexpected T_STRING in /websites/LinuxPackage05/4v/35/xy/4v35xy-55415.webfusion-hosting.co.uk/public_html/noff-group.com/dev/add_to_cart.php on line 27

Thanks in advance.

like image 550
Tom Avatar asked Nov 28 '25 17:11

Tom


1 Answers

From the manual:

For LAST_INSERT_ID(), the most recently generated ID is maintained in the server on a per-connection basis. It is not changed by another client. It is not even changed if you update another AUTO_INCREMENT column with a nonmagic value (that is, a value that is not NULL and not 0). Using LAST_INSERT_ID() and AUTO_INCREMENT columns simultaneously from multiple clients is perfectly valid. Each client will receive the last inserted ID for the last statement that client executed.

like image 57
jensgram Avatar answered Nov 30 '25 06:11

jensgram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!