简体   繁体   中英

How do i get the SQL query ID after processing it?

This a bit looks complicated, i want to get the id column value of the processed query.

example:

$qu = mysql_query("INSERT INTO msgs (msg,stamp) VALUES('$v1','$v2')");  

i want to get the ID of this query after storing the infos in database.

if it's impossible, is getting the last ID record and adding 1 will be safe and guaranteed?

Note: i use PHP and mySQL

Thanks

如果它是auto_increment列,请使用PHP函数mysql_insert_id。

If you are using standard mysql in PHP, all you have to do, is to use mysql_insert_id() which takes resource $link as parameter (your mysql connection)

http://php.net/manual/en/function.mysql-insert-id.php

Basic usage:

<?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 ('some product')");

    echo 'Last inserted record has id of ' . mysql_insert_id();
?>

No, it is not safe to grab the highest id and just add 1 and use that as the new id. This is what's known as a race condition. If two queries attempt to do this operation at the same time, it could be that they both select the SAME highest id, both attempt to add 1, and then BOTH attempt to use the same id (which would be bad).

It's much better to use AUTO_INCREMENT fields as you're doing, and you can retrieve the inserted id in PHP as follows (from http://php.net/manual/en/function.mysql-insert-id.php ):

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

Here's the code:

$qu = mysql_query("INSERT INTO msgs (msg,stamp) VALUES('$v1','$v2')"); 
$recent_id = mysql_insert_id();

The variable recent_id is what you are looking for.

Getting the last ID record and adding 1 MAY NOT be safe and IS NOT guaranteed. You are better off using the solution that I have indicated if you really want to play it safe.

Hope it helps.

Hope this helps:

int mysql_insert_id ([ resource $link_identifier ] )

http://us3.php.net/mysql_insert_id

检查这里,如果您使用mysqli for php没问题

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM