php mysqli 最后插入 id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19738283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:56:42  来源:igfitidea点击:

mysqli last insert id

phpmysqlmysqlilastinsertid

提问by user2926655

I would like to associate the image with firstname, lastname...how can I retrieve the last rowand use it to insert to the other table? I tried $image = $mysqli->insert_id;then binding but it doesn't work. Can someone help me out?

我想将图像与名字、姓氏相关联...如何检索最后一行并使用它插入到另一个表中?我尝试$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();

回答by Abdallah Alhabarneh

mysqli::$insert_id-- mysqli_insert_id— Returns the auto generated id used in the last query, Example:

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();

output

输出

New Record has id 1.

新记录的 ID 为 1。

Reference

参考

回答by Rathod Paresh

First of All you need to create auto_increment field in you ID

首先,您需要在 ID 中创建 auto_increment 字段

Then You can used $last_id = mysqli_insert_id($conn);

然后你可以使用 $last_id = mysqli_insert_id($conn);

回答by Your Common Sense

after I get the last row from table2 I would like to insert it to table1. That is all I need

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

Go on:

继续:

  1. insert into table 1 with simple regular insert query
  2. get last insert id
  3. insert into table 2 with simple regular insert query
  1. 使用简单的常规插入查询插入表 1
  2. 获取最后一个插入 ID
  3. 使用简单的常规插入查询插入表 2

As simple as that

就如此容易