mysqli last insert id

2022-08-30 17:04:28

我想将图像与名字,姓氏相关联...如何检索最后一行并使用它来插入到另一个表中?我尝试绑定,但它不起作用。有人可以帮助我吗?$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();

答案 1

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。

参考


答案 2

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

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


推荐