Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to return the id of a row that was just created in MySQL with PHP?

Tags:

php

mysql

When I create a new entry in my MySQL database, I'd like the query to return the id of the table that was just created. If it cannot do this, is there another way to find out the this id? The reason I want to do this is so I can link a new row to the row that spawned it (and there's no guarantee that they're consecutive)

like image 612
chustar Avatar asked Nov 30 '22 07:11

chustar


1 Answers

You mean last autoincrement id?

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
like image 133
Alekc Avatar answered Dec 01 '22 21:12

Alekc