在最后一个之前获取查询的最后一个插入ID?

时间:2013-06-08 21:42:51

标签: mysql pdo

如何获取主题ID?所以我可以在发布后将用户重定向到他的主题? 如果我切换它然后我不能在帖子中插入topic_id。 HMM。

$stmt = $db->prepare("INSERT INTO topics (subject, posted, first_post_id, last_post, last_post_id, forum_id) 
VALUES (:subject,:posted,:first_post_id,:last_post,:last_post_id,:forum_id)");
$stmt->execute(array(':subject'=>$subject,':posted'=>time(),':first_post_id'=>$cid,':last_post'=>time(),':last_post_id'=>$cid,':forum_id'=>$f));


$stmt = $db->prepare("INSERT INTO posts (poster_id, poster_ip, message, posted, topic_id) 
 VALUES (:poster_id,:poster_ip,:message,:posted,:topic_id)");
$stmt->execute(array(':poster_id'=>$cid,':poster_ip'=>$_SERVER['REMOTE_ADDR'],':message'=>$message,':posted'=>time(),':topic_id'=>$db->lastInsertId()));




header("Location: /thread/".$db->lastInsertId()); // This will get the post ID not topic ID that i want it to

1 个答案:

答案 0 :(得分:0)

使用临时变量:

$stmt = $db->prepare(/* FIRST QUERY */);
$stmt->execute();

$temp = $db->lastInsertId();

$stmt = $db->prepare(/* SECOND QUERY */);
$stmt->execute();

header("Location: /thread/".$temp);