views:

132

answers:

3

Can I get from PHP a value back like the new id from the row I've just added to the database or should I make a SELECT to retrieve it?

<?php

$sql = "INSERT INTO my_table (column_1, column_2) VALUES ('hello', 'ciao')";
$res = mysql_query ($sql) or die (mysql_error ());

$sql = "SELECT column_id FROM my_table WHERE column_1 = 'hello'";
$res = mysql_query ($sql) or die (mysql_error ());

$row = mysql_fetch_assoc ($res);
$id = $row["column_id"];
print "my id is = $id";

?>
A: 

There is builtin support for it, mysql_insert_id() or something.

jishi
+2  A: 

Use this: http://php.net/manual/en/function.mysql-insert-id.php Selecting can be dangerous because an auto-increment often means that records may not otherwise be unique, and therefore not uniquely selectable without the id.

Eric Mickelsen
thanks for help
Vittorio Vittori
A: 

The proper way of getting the id is via mysql_insert_id(), as others have stated. The reason for this is that you may have other inserts taking place immediately following yours, and simply requesting the last id is not guaranteed to return the id that you expected.

$result = mysql_query("INSERT INTO tableName (col1) VALUES ('foo')");

print mysql_insert_id();
Jonathan Sampson