开发者

How to insert the last id from a table into another table in MySQL?

开发者 https://www.devze.com 2022-12-25 00:48 出处:网络
I want to take the id of the most recent item in a database, increment it by one and insert that new id in to anot开发者_Go百科her table.

I want to take the id of the most recent item in a database, increment it by one and insert that new id in to anot开发者_Go百科her table.

I tried:

$select = mysql_query("SELECT id FROM tableName ORDER BY id DESC");

while ($return = mysql_fetch_assoc($select)) {

   $id = $return['id'];
   $newId = $id++;

}

mysql_query("INSERT INTO anotherTable (someColumn) VALUES ('$newId')");

But it didn't work. How can this be done?


You should not do this. Instead insert a new record into tableName then use mysql_insert_id() to capture the new ID and then insert it into anotherTable. This way you avoid race conditions that could happen if you did it the other way around.


Use mysql_insert_id() to get the last inserted ID


Why are you using a while statement? If you only want the most recent id, just take the while out..

$select = mysql_query("SELECT id FROM tableName ORDER BY id DESC");

$return = mysql_fetch_assoc($select);

$id = $return['id'];
$newId = $id + 1;

mysql_query("INSERT INTO anotherTable (someColumn) VALUES ('$newId')");


You can try this:

$select = mysql_query("SELECT id FROM tableName ORDER BY id DESC");

if(! $select)
    die("Query Failed");

$return = mysql_fetch_assoc($select);
$id = $return['id'];
$newId = ++ $id; // post increment does not work...use preincrement.
mysql_query("INSERT INTO anotherTable (someColumn) VALUES ('$newId')");
0

精彩评论

暂无评论...
验证码 换一张
取 消