mysqli最后插入的ID

26

我希望将图像与名字和姓氏相关联... 我如何检索最后一行并使用它插入到另一个表中? 我尝试了$image = $mysqli->insert_id;然后绑定,但它不起作用。 有人能帮我吗?

 $image = $mysqli->insert_id;//this should come from table2
 $stmt = $mysqli->prepare("
  insert into table1 (username, firstname, lastname, image) 
  select ?,?,?,image from table2 t2 where username = ? and  t2.id = ? 
   ");
 $stmt->bind_param('sssss', $username, $fname, $lname, $username, $image);
 $stmt->execute();

4
在执行插入查询后,您需要使用 insert_id;,例如:if ($stmt->execute()) $image = $stmt->insert_id;。这将返回插入行的ID,并将其分配给 $image 变量。请注意不要改变原始意思。 - Iłya Bursov
@IlyaBursov那么如何绑定t2.id = ?? - user2926655
你需要以更清晰明确的方式表达你的愿望。 - Your Common Sense
@user2926655 你想插入到table1还是table2? - Iłya Bursov
1
@NicoHaase,你很难得到回答,因为原帖发布者已经在7年前离开了这个网站。 - Your Common Sense
显示剩余7条评论
3个回答

32

mysqli::$insert_id -- mysqli_insert_id — 返回上次查询中使用的自动生成的 ID,例如:

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

/* drop table */
$mysqli->query("DROP TABLE myCity");

/* close connection */
$mysqli->close();

输出

新增记录的 ID 是 1。

参考资料


1
请问您能否解释一下为什么需要创建一个新表? - Veer Shrivastav

19
首先,您需要在您的ID中创建自动增量字段。
然后,您可以使用以下代码: $last_id = mysqli_insert_id($conn);

1

在从table2获取到最后一行之后,我希望将其插入到table1中。这就是我所需要的。

继续:

  1. 使用简单的常规插入查询将数据插入到table1中
  2. 获取最后插入的id
  3. 使用简单的常规插入查询将数据插入到table2中

就这么简单。


如果你没有反转表名,你的答案在概念上是正确的。 - MLK.DEV

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接