The mysqli_stmt::$insert_id() function is used to obtain the autoincrement ID value of the last insertion operation. It returns an integer representing the autoincrement ID generated by the last insertion operation.
usage:
The sample code is as follows:
// 创建mysqli连接$conn = new mysqli("localhost", "username", "password", "database"); // 检查连接是否成功if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 准备SQL语句$sql = "INSERT INTO table_name (column1, column2) VALUES (?, ?)"; $stmt = $conn->prepare($sql); // 绑定参数$stmt->bind_param("ss", $value1, $value2); // 设置参数值$value1 = "John"; $value2 = "Doe"; // 执行SQL语句$stmt->execute(); // 获取最后一次插入操作的自增ID值$insertId = $stmt->insert_id; // 输出结果echo "最后一次插入操作的自增ID值为: " . $insertId; // 关闭连接$stmt->close(); $conn->close();
In the above example, we first create a mysqli connection and prepare an INSERT statement. Then, we bind the parameters and set the parameter value. After executing the SQL statement, we get the auto-increment ID value of the last insertion operation by calling the mysqli_stmt::$insert_id() function. Finally, we output the value to the screen.
Note that before using the mysqli_stmt::$insert_id() function, the insert operation must be performed first, otherwise 0 will be returned. In addition, this function can only obtain the autoincrement ID value of the last insertion operation generated by the current connection.