php Mysql问题与联合表中的准备查询

时间:2017-03-30 20:25:31

标签: php mysql

我正在创建一个应用,我在Blog帖子和评论之间有一个联合表。 所以,假设我有一个包含帖子列表的页面,当我想查看详细信息视图时,我将该帖子的ID放在url中的参数中,我在我的应用程序中的某个位置保存了我的安装程序。 在该帖子的详细视图中,我有一个表单来添加评论;但是,当我尝试插入帖子和评论本身的ID时,这里不起作用的是我的查询/方法:

Public function insertPost(Articles $article)
    {
//here I insert the comment
        $sql = $this->getBdd()->prepare('INSERT INTO comments(comment, date_comment) 
                                                    VALUES (?,NOW())');
        $sql->execute(array($article->getContent()));

//here I try to insert the ID of the comment and the related ID of my post (since I added the class as a dependency in my method I can still get the id)
        $sql2 = $this->getBdd()->prepare('
INSERT INTO joint_a_comments(id_comment,id_article)
SELECT comments.id, articles.id
FROM comments, articles
WHERE comments.id = (SELECT id FROM comments ORDER BY id DESC LIMIT 0,1)
                                                    AND articles.id = "'.$article->getId().'" ');
        $sql2->execute();
    }

你们有没有看错?

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

插入评论后,我们可以抓住评论ID和文章ID,如下所示:

$sql = $this->getBdd()->prepare('INSERT INTO comments(comment, date_comment) VALUES (?,NOW())');
$sql->execute(array($article->getContent()));

$comment_id = $this->getBdd()->lastInsertId();

$article_id = $article->getId();

$sql2 = $this->getBdd()->prepare('
INSERT INTO joint_a_comments(id_comment,id_article) VALUES(?, ?)');

 $sql2->execute([$comment_id, $article_id]);

答案 1 :(得分:0)

如果idAUTO_INCREMENT列,则可以在执行第一个SELECT LAST_INSERT_ID()语句后立即使用INSERTLAST_INSERT_ID()将返回AUTO_INCREMENT列的插入值。

试试这个:

public function insertPost(Articles $article)
{
    $db = $this->getBdd();
    //here I insert the comment
    $sql = $db->prepare(
        'INSERT INTO comments(comment, date_comment) VALUES (?,NOW())'
    );

    $sql->execute(array($article->getContent()));
    $commentId = $db->query('SELECT LAST_INSERT_ID()')->fetchColumn();


    //here I try to insert the ID of the comment and the related ID of my post (since I added the class as a dependency in my method I can still get the id)
    $sql2 = $db->prepare(
        'INSERT INTO joint_a_comments(id_comment,id_article)
            SELECT comments.id, articles.id
            FROM comments, articles
            WHERE
                comments.id = ? AND
                articles.id = ?'
    );

    $sql2->execute([$commentId, $article->getId()]);
}