php检索插入的最后一条记录的id并将其插入到另一个表中

发布于 2024-09-03 19:48:07 字数 593 浏览 3 评论 0原文

我正在尝试检索插入到“authors”表中的最后一条记录的 id,并将检索到的 id 插入到“articles”表中;这是我的代码:

$title = mysql_real_escape_string($_POST[title]);
$body = mysql_real_escape_string($_POST[body]);
$category = mysql_real_escape_string($_POST[category]);

$insert_author="INSERT INTO authors (name) VALUES ('$title')";
$select_author= mysql_query("SELECT LAST_INSERT_ID()");

$authId = mysql_fetch_array($select_author);
$query="INSERT INTO articles (body, date, category, auth_id) VALUES ('$body', '$date_now', '$category', '$authId')";

这不起作用...

有什么想法吗?

预先感谢

毛罗

I'm trying to retrieve the id of the last record inserted in the table 'authors' and insert the retrieved id in the 'articles' table; here's my code:

$title = mysql_real_escape_string($_POST[title]);
$body = mysql_real_escape_string($_POST[body]);
$category = mysql_real_escape_string($_POST[category]);

$insert_author="INSERT INTO authors (name) VALUES ('$title')";
$select_author= mysql_query("SELECT LAST_INSERT_ID()");

$authId = mysql_fetch_array($select_author);
$query="INSERT INTO articles (body, date, category, auth_id) VALUES ('$body', '$date_now', '$category', '$authId')";

this doesn't work...

Any idea please?

Thanks in Advance

Mauro

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

猛虎独行 2024-09-10 19:48:07

您可以使用 mysql_insert_id( )

$insert_author="INSERT INTO authors (name) VALUES ('$title')";
mysql_query($insert_author) or die(mysql_error());

$authId = mysql_insert_id();

$query="INSERT INTO articles (body, date, category, auth_id) VALUES
('$body', '$date_now', '$category', '$authId')";

注意,您缺少用于插入查询的 mysql_query 函数,我也在上面的代码中添加了该函数。

You can get the last insert id with mysql_insert_id()

$insert_author="INSERT INTO authors (name) VALUES ('$title')";
mysql_query($insert_author) or die(mysql_error());

$authId = mysql_insert_id();

$query="INSERT INTO articles (body, date, category, auth_id) VALUES
('$body', '$date_now', '$category', '$authId')";

Note that you were missing mysql_query function for insert query, i have added that also in code above.

记忆里有你的影子 2024-09-10 19:48:07

究竟是什么不起作用。 $authId 是否包含预期值?你把它扔出去检查了吗?

除此之外,您忘记了第二个mysql_query()

What exactly doesn't work. Do the $authId contains the expected value? Did you dump it to check?

Apart from that, you forgot the second mysql_query().

∞梦里开花 2024-09-10 19:48:07

尝试使用 mysql-insert-id 代替。

Try mysql-insert-id instead.

顾忌 2024-09-10 19:48:07

顾名思义,mysql_fetch_array($select_author) 返回一个数组,因此您需要获取该数组中的特定值以插入到另一个表中。

As the name says, mysql_fetch_array($select_author) returns an array so you will need to get the specific value in that array to insert in the other table.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文