我该如何解释这个......
基本上说,如果我创建一个帖子,我单击提交,就会发生以下数据库插入
$sql="INSERT INTO comments (userid, topicid, category, topicname, comment, date, name, avatar)
VALUES
('$row[id]','$content[id]','blogs','$content[topic]','$_POST[comment]','$today','$row[name]', '$row[cavatar]')";
现在说在该帖子的同时我想要运行另一个 INSERT 查询,如何将第一个查询中的 AUTO 创建的 ID 号获取到第二个查询中?
第二个查询是
$notifyme="INSERT INTO notifyme (userid, catid, category, date,time)
VALUES
('$row[id]', ,'comments','$date','$time')";
它们同时运行,但我需要在 QUERY 1 上自动创建的 ID 号插入到 QUERY 2 的 CATID 下
$sql="INSERT INTO comments (userid, topicid, category, topicname, comment, date, name, avatar)
VALUES
('$row[id]','$content[id]','blogs','$content[topic]','$_POST[comment]','$today','$row[name]','$row[cavatar]')";
$notifyme="INSERT INTO notifyme (userid, catid, category, date,time)
VALUES
('$row[id]', ,'comments','$date','$time')";
这是运行时的样子,两者将同时运行
最佳答案
由于您在评论中表示您正在使用 mysqli_
API 进行连接,因此请在每次查询运行后使用 mysqli_insert_id()
检索记录 ID。
引用:
<小时/>旁注:
您当前的代码已开放给 SQL injection 。使用prepared statements ,或PDO with prepared statements ,它们更安全。
关于php - 插入数据库时如何获取ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30605791/