SELECT LAST_INSERT_ID()*已更新

时间:2011-01-13 00:23:36

标签: php mysql lastinsertid

我想使用SELECT LAST_INSERT_ID() 我使用表单来获得用户输入值。使用第一个插入,我需要获取下一个插入的最后一个插入ID ...我还没弄明白如何获取最后选择的ID,然后将其传递给我的第二个插入语句

我已经更新了我的代码,但仍然无法将id发布到表格中

include("config.inc.php");
$link = mysql_connect($db_host,$db_user,$db_pass);
if(!$link) die ('Could not connect to database: '.mysql_error());
mysql_select_db($db_name,$link);
$query = "INSERT into `".$db_table."` (producer_id,series_id,lang_id,title_name,title_public_access) VALUES ('" . $_POST['producer_id'] . "','" . $_POST['series_id'] . "','" . $_POST['lang_id'] . "','" . $_POST['title_name'] . "','" . $_POST['title_public_access'] . "')";

$last_id = mysql_insert_id();

$query = "INSERT into `".$db_table2."` (seg_id, file_video_UNC,file_video_URL) VALUES ('" . '$last_id' . "','" . $_POST['file_video_UNC'] . "','" . $_POST['file_video_URL'] . "')";

mysql_query($query);
mysql_close($link);

3 个答案:

答案 0 :(得分:2)

有一个功能,称为mysql_insert_id()

... first query here ...
$last_id = mysql_insert_id();
$sql = "INSERT INTO $db_table SET 
    file_video = " . $_POST['file_video_UNC'].",
    file_video_URL = " . $_POST['file_video_URL'] . ",
    insert_id_of_first_query = $last_id";
...

您更新的代码不会将查询发送到数据库 - 因此没有INSERT,因此没有LAST_INSERT_ID

$query = "INSERT into ".$db_table." 
    (producer_id,series_id,lang_id,title_name,title_public_access) VALUES
    ('" . $_POST['producer_id'] . "','" 
        . $_POST['series_id'] . "','" 
        . $_POST['lang_id'] . "','" . $_POST['title_name'] . "','" 
        . $_POST['title_public_access'] . "')";

mysql_query($query); /* YOU FORGOT THIS PART */
$last_id = mysql_insert_id();

答案 1 :(得分:1)

您不能仅在PHP行中将查询转储到字符串中。您应该在第二个查询中使用LAST_INSERT_ID(),或者更好的是,使用PHP's mysql_insert_id()函数在API中为您包装。

答案 2 :(得分:0)

在行中:

$query = "INSERT into `".$db_table2."` (seg_id, file_video_UNC,file_video_URL) VALUES ('" . '$last_id' . "','" . $_POST['file_video_UNC'] . "','" . $_POST['file_video_URL'] . "')";

我认为VALUES ('" . '$last_id' . "',应该是VALUES ('" . $last_id . "',而不是变量周围的单引号。