这个例子缺少 multi_query 中的 insert_id。这是我的例子
假设你在 mysql 中有一个新的 test_db,如下所示
create database if not exists test_db;
use test_db;
create table user_info (_id serial, name varchar(100) not null);
create table house_info (_id serial, address varchar(100) not null);
然后你运行一个像这样的 php 文件
<?php
define('SERVER', '127.0.01');
define('MYSQL_USER', 'your_user_name');
define('MYSQL_PASSWORD', 'your_password');
$db = new mysqli(SERVER, MYSQL_USER, MYSQL_PASSWORD, "test_db", 3306);
if ($db->connect_errno)
echo "create db failed, error is ", $db->connect_error;
else {
$sql = "insert into user_info "
. "(name) values "
. "('owen'), ('john'), ('lily')";
if (!$result = $db->query($sql))
echo "insert failed, error: ", $db->error;
else
echo "last insert id in query is ", $db->insert_id, "\n";
$sql = "insert into user_info"
. "(name) values "
. "('jim');";
$sql .= "insert into house_info "
. "(address) values "
. "('shenyang')";
if (!$db->multi_query($sql))
echo "insert failed in multi_query, error: ", $db->error;
else {
echo "last insert id in first multi_query is ", $db->insert_id, "\n";
if ($db->more_results() && $db->next_result())
echo "last insert id in second multi_query is ", $db->insert_id, "\n";
else
echo "insert failed in multi_query, second query error is ", $db->error;
}
$db->close();
}
?>
你将获得类似这样的输出
last insert id in query is 1
last insert id in first multi_query is 4
last insert id in second multi_query is 1
结论
1 insert_id 在 multi_query 中有效
2 如果你进行多值插入,insert_id 是 mysql 使用的第一个 ID