从插入数据的数据库中获取行的ID

时间:2013-08-08 12:38:58

标签: php mysql database

我正在运行MySQL INSERT查询,我将一些数据插入到数据库中。 每次添加新条目时,每行都会生成一个唯一的ID。我想在插入数据后直接获得此ID。

PHP代码:

$addGiveawayToDb = mysql_query("INSERT INTO $table(orientation, title, color) 
    VALUES ('$orientation', '$title', '$color')") 
    or die(mysql_error());
//Here I need to get the row id of the above data...

谢谢!

1 个答案:

答案 0 :(得分:4)

尝试

$addGiveawayToDb = mysql_query("INSERT INTO $table(orientation, title, color) 
VALUES ('$orientation', '$title', '$color')") 
or die(mysql_error());

echo "Inserted Id is ".mysql_insert_id();

确保您的表中有自动增量字段。并且还尝试避免使用mysql_*函数,因为它们已被弃用。请使用mysqli_*函数或PDO语句。

请参阅此LINK

相关问题