PHP/MySQL insert row then get #39;id#39;(PHP/MySQL 插入行然后获取 id)
问题描述
The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.
I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?
I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.
$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);
See mysqli_insert_id()
.
Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable
". Like you say, it's a race condition and there's no need. mysqli_insert_id()
already has this functionality.
Another way would be to run both queries in one go, and using MySQL
's LAST_INSERT_ID()
method, where both tables get modified at once (and PHP does not need any ID), like:
mysqli_query($link, "INSERT INTO my_user_table ...;
INSERT INTO my_other_table (`user_id`) VALUES (LAST_INSERT_ID())");
Note that Each connection keeps track of ID separately (so, conflicts are prevented already).
这篇关于PHP/MySQL 插入行然后获取 'id'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP/MySQL 插入行然后获取 'id'
基础教程推荐
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在多维数组中查找最大值 2021-01-01