我正在从头开始构建一个论坛系统,而且我在代码中遇到了一个小麻烦。代码如下所示:
function post($title, $body, $uid, $visible)
{
if(strlen($title) <= 0 || strlen($body) <= 0)
{
return false;
}
else
{
$sql = "INSERT INTO user_threads(title,uid,postDate) VALUES(:title, :uid, NOW()); SELECT threadID FROM user_threads WHERE title = :title2 AND uid = :uid2;";
$que = $this->db->prepare($sql);
$que->bindParam(':title', $title);
$que->bindParam(':title2', $title);
$que->bindParam(':uid', $uid);
$que->bindParam(':uid2', $uid);
try {
$que->execute();
$que->nextRowset();
$row = $que->fetch(PDO::FETCH_BOTH);
$sql = "INSERT INTO thread_messages(threadID, message_body, poster) VALUES (:row, :body, :uid)";
$que = $this->db->prepare($sql);
$que->bindParam(':row', $row[0]);
$que->bindParam(':body', $body);
$que->bindParam(':uid', $uid);
try { $que->execute(); }catch(PDOException $e){}
}catch(PDOException $e){}
}
}
现在......我以为自己在做这个方面很聪明,但结果却根本不起作用。如果用户创建了两个具有相同标题(测试和测试)的主题,那么他们发布的消息将仅在一个主题下可见,而不是两个不同的主题。
答案 0 :(得分:0)
如果您的threadID列是自动增量列,则不需要在第一个字符串中包含第二个查询。只需使用PDO::lastInsertId()
方法从第一个查询中获取生成的自动增量ID:
$sql = "INSERT INTO user_threads(title,uid,postDate) VALUES(:title, :uid, NOW())";
$que = $this->db->prepare($sql);
$que->bindParam(':title', $title);
$que->bindParam(':uid', $uid);
try
{
$que->execute();
$threadID = $this->db->lastInsertId();
$sql = "INSERT INTO thread_messages(threadID, message_body, poster) VALUES (:row, :body, :uid)";
$que = $this->db->prepare($sql);
$que->bindParam(':row', $threadID);
$que->bindParam(':body', $body);
$que->bindParam(':uid', $uid);
try { $que->execute(); }catch(PDOException $e){}
}
catch(PDOException $e){}