2010-01-07 80 views
1

之後獲得一個列值(如id)我可以從PHP中獲得一個值,就像我剛剛添加到數據庫的行中的新ID一樣,或者我應該使用SELECT來檢索它?mysql INSERT

<?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"; 

?> 

回答

0

有內置的支持,mysql_insert_id()或其他東西。

1

正如其他人所說,獲取該ID的正確方法是通過mysql_insert_id()。原因是您可能會在您的後面立即發生其他插入,並且只是要求最後的id不能保證返回您所期望的id

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

print mysql_insert_id();