Вопрос

I can't get latest insert id. This is my php code:

$query='INSERT INTO candidates (company_id, name, surname, address1, address2, city, county, postcode, cv, skills, distance) VALUES (10254, \'name\', \'surname\', \'1st Floor\', \'Street\', \'City\', \'County\', \'postcode\', \'0\', \'#6#,#3#,#2#,#1#,\', 25)';
$sql = mysql_query($query, $jobboard) or die(mysql_error());
$res = mysql_query('SELECT LAST_INSERT_ID() FROM candidates AS ID',$jobboard);

When I put query 'SELECT LAST_INSERT_ID() FROM candidates' straight in MySQL in return I get as many record as I have in this table, all values are 0. For example right now I have 5 records, id are 2,3,4,5,6 (I removed 1st), I get this table:
LAST_INSERT_ID()
0
0
0
0
0

How can I get latest insert record ID? BTW 1 only column is AUTO_INCREMENT, which is id.

Это было полезно?

Решение

mysql_insert_id()

That all

Documentation on mysql_insert_id

Другие советы

You want to use the mysql_insert_id() function to get the last ID like this:

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

On that note, you also want to move to newer, shinier, safer PHP PDO - all the benefits of the old depreciated mysql_* functions without the headaches and STDs :)

Just by using mysql_insert_id(); you can get the lase inserted id in databse.In you case you can use like this:

$query='INSERT INTO candidates (company_id, name, surname, address1, address2, city, county, postcode, cv, skills, distance) VALUES (10254, \'name\', \'surname\', \'1st Floor\', \'Street\', \'City\', \'County\', \'postcode\', \'0\', \'#6#,#3#,#2#,#1#,\', 25)';
$sql = mysql_query($query, $jobboard) or die(mysql_error());
$last_id=mysql_insert_id();//get last inserted id.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top