php检索插入的最后一条记录的id并将其插入到另一个表中
我正在尝试检索插入到“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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
mysql_insert_id( )
注意,您缺少用于插入查询的
mysql_query
函数,我也在上面的代码中添加了该函数。You can get the last insert id with
mysql_insert_id()
Note that you were missing
mysql_query
function for insert query, i have added that also in code above.究竟是什么不起作用。
$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()
.尝试使用 mysql-insert-id 代替。
Try mysql-insert-id instead.
顾名思义,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.