1

我正在寻找使用 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);
4

3 回答 3

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

您更新的代码不会将查询发送到数据库 - 结果 no INSERT,所以 noLAST_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();
于 2011-01-13T00:28:50.400 回答
1

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

于 2011-01-13T00:29:54.363 回答
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'] . "')";

I think VALUES ('" . '$last_id' . "', should just be VALUES ('" . $last_id . "', without the single quotes around the variable.

于 2013-04-12T10:52:20.813 回答