tags:

views:

62

answers:

4

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 another 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?

+4  A: 

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.

Ignacio Vazquez-Abrams
+1  A: 

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')");
Brendan Long
A: 

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')");
codaddict
Great, thanks I needed to remove the while. For some odd reason $newId = $id++ doesn't work but $newId = $id + 1 does.
James
Dunno why this was modded -1...
Brendan Long
+1  A: 

Use mysql_insert_id() to get the last inserted ID

OM The Eternity