mysqli last insert id

*爱你&永不变心* 提交于 2021-01-29 15:56:41

问题


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;//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 — Returns the auto generated id used in the last query, Example:

$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.

Reference

  • PHP mysqli_insert_id: http://www.php.net/manual/en/mysqli.insert-id.php



回答2:


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

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




回答3:


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

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

As simple as that



来源:https://stackoverflow.com/questions/61474888/get-id-from-previous-insert-and-use-as-a-reference-record-for-another-table-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!