Get a column value (like id) after mysql INSERT
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 co开发者_运维知识库lumn_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";
?>
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.
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();
There is builtin support for it, mysql_insert_id() or something.
精彩评论