php - MySQL - 在插入时返回生成的 AUTO_INCREMENT 值

标签 php mysql

希望是一个简单的解决方案 - 我想不出一个可靠的解决方案。

我正在构建一个生成 id_cart AUTO_INCREMENT 主键的购物车机制。购物车项目有另一个表,其中包含购物车产品变量,如尺寸。我想在尺码表中归因于相同的 id_cart。

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

我见过 SELECT LAST_INSERT_ID()。

确保它是最后插入的 ID 有多稳固?不想让顾客买错尺码!

__ 编辑 ___

感谢您的输入。尽管如此,我还是遇到了麻烦。请参阅下面的实际代码;

//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;

错误显示为

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

提前致谢。

最佳答案

来自 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.

关于php - MySQL - 在插入时返回生成的 AUTO_INCREMENT 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8896447/

相关文章:

php - $wp_query->max_num_pages 不适用于 CPT

php - 如何从 `<td>`内的文本添加分号然后通过ajax发送

mysql - 求和不同的 MYSQL | WHERE条款

php - 选择和删除行mysqli查询

php - MySQL右查询左加入图像表中最新上传的图像,分页

php - 使用Youtube API获取JSON时,使用哪个IP?托管的还是用户的?

php - 显示两个不同表中的数据

php - 如何更改 docker jwilder/nginx-proxy 上传限制?

php - html提交按钮不起作用

java - 在数据库中创建表导致很多异常