Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysqli last insert id

Tags:

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(); 
like image 576
user2926655 Avatar asked Nov 02 '13 02:11

user2926655


People also ask

How do I get last INSERT ID?

Get ID of The Last Inserted RecordIf we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get the ID of the last inserted/updated record immediately.

How do I get the last inserted id in mysql?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.

What is mysqli_insert_id?

mysqli_insert_id(mysqli $mysql ): int|string. Returns the ID generated by an INSERT or UPDATE query on a table with a column having the AUTO_INCREMENT attribute. In the case of a multiple-row INSERT statement, it returns the first automatically generated value that was successfully inserted.

How can I get last inserted record in mysql using PHP?

If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.


1 Answers

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
like image 97
abe Avatar answered Sep 19 '22 10:09

abe