Fonction modification de commentaire (PHP en MVC)

a marqué ce sujet comme résolu.

Bonjour à tous,

je sollicite votre aide concernant l’ajout d’une fonctionnalité "Modification du commentaire" que je dois ajouter dans le cadre d’un exercice de la création d’un blog, j’ai essayé tant bien que mal de rédiger les ajouts dans : mon router, mon controller, la class concernée, ainsi que ma view. Je m’emmêle les pinceaux, je suis encore vraiment débutant et ne parvient plus à être à l’aise avec autant de fichiers/code, le problème c’est que lorsque je clique sur le lien de modification qui se situe à chaque commentaire, j’arrive sur le formulaire de modification, l’id du commentaire est relevé dans l’URL, le formulaire est là, avec les champs vides mais lorsque je sollicite le submit, rien ne se passe… Le debuggeur m’indique que la variable $post est non définie, il m’a aussi dit qu’elle est demandée comme un array mais qu’elle retournait fausse…

Voici mon router index.php

<?php
require('C:\laragon\www\p5\controller\frontend.php');

try { // On essaie de faire des choses
    if (isset($_GET['action'])) {
        if ($_GET['action'] == 'listPosts') {
            listPosts();
        }
        elseif ($_GET['action'] == 'post') {
            if (isset($_GET['id']) && $_GET['id'] > 0) {
                post();
            }
            else {
                // Erreur ! On arrête tout, on envoie une exception, donc au saute directement au catch
                throw new Exception('Aucun identifiant de billet envoyé');
            }
        }
        elseif ($_GET['action'] == 'addComment') {
            if (isset($_GET['id']) && $_GET['id'] > 0) {
                if (!empty($_POST['author']) && !empty($_POST['comment'])) {
                    addComment($_GET['id'], $_POST['author'], $_POST['comment']);
                }
                else {
                    // Autre exception
                    throw new Exception('Tous les champs ne sont pas remplis !');
                }
            }
          }
        elseif ($_GET['action'] == "viewComment"){
            if(isset($_GET['id']) && $_GET['id'] > 0){
              viewComment();
            }
            else {
                // Erreur ! On arrête tout, on envoie une exception, donc au saute directement au catch
                throw new Exception('Aucun id de commentaire envoyé');
            }
          }
        elseif($_GET['action'] == "updateComment"){
            if (isset($_GET['id']) && $_GET['id'] > 0)
            {
            if (!empty($_POST['author']) && !empty($_POST['comment']))
                {
                updateComment($_GET['id'], $_POST['author'], $_POST['comment'], $_GET['comment_id']);
                }
            else{
                // Autre exception
                throw new Exception('Aucun identifiant de billet envoyé');
            }
        }     
    }     

    }

    else 
    {
        listPosts();
    }

} 
    catch(Exception $e) {
    echo 'Erreur : ' . $e->getMessage();
}

Voici mon controller frontend.php

<?php

// Chargement des classes
require_once('C:\laragon\www\p5\model\PostManager.php');
require_once('C:\laragon\www\p5\model\CommentManager.php');

function listPosts()
{
    $postManager = new PostManager(); // Création d'un objet
    $posts = $postManager->getPosts(); // Appel d'une fonction de cet objet pour recuperer les posts

    require('C:\laragon\www\p5\view\frontend\listPostView.php');

}

function post()
{   // Création d'objets (et non variables ! )
    $postManager = new PostManager();
    $commentManager = new CommentManager();
    // Les variables $post et $comment appellent via des objets : des fonctions
    // Fonction membre et public : getPost et getComments qui récupèrent l'id du post ou commentaire dans l'URL
    $post = $postManager->getPost($_GET['id']);
    $comments = $commentManager->getComments($_GET['id']);
    
    require('C:\laragon\www\p5\view\frontend\postView.php');
}

function viewComment(){

    $postManager = new PostManager();
    $commentManager = new CommentManager();

    // $post = $postManager->getPost($_GET['id']);
    $comment = $commentManager->getComment($_GET['id']);

    require 'C:\laragon\www\p5\view\frontend\commentView.php';

}

function addComment($postId, $author, $comment)

{   // Declare que $commentManager est l'objet (et non la variable) de la classe CommentManager
    $commentManager = new CommentManager();
    // test si toutes les lignes sont présentes en appelant la fonction membre public postComment de la class CommentManager
    $affectedLines = $commentManager->postComment($postId, $author, $comment);
    // si il ya un probleme avec une ligne, on jète une exception qui sera catch dans index.php
    if ($affectedLines === false) {
        throw new Exception('Impossible d\'ajouter le commentaire !');
    } 
    // Si tout se passe bien, redirection grace au header pour afficher le nouveau commentaire !
    else {
        header('Location: index.php?action=post&id=' . $postId);
    }
}

function updateComment($postId, $author, $comment, $commentId)
{
    $commentManager = new CommentManager();

    $affectedLines = $commentManager->changeComment($postId, $author, $comment, $commentId);

    if ($affectedLines === false) {
        throw new Exception('Impossible de modifier le commentaire !');
    }
    else {
        header('Location: index.php?action=post&id='. $postId);
    }
}

Voici mon model frontend.php


<?php

// affiche la liste des posts
function getPosts()
{
    $db = dbConnect();
    $req = $db->query('SELECT id, title, content, DATE_FORMAT(creation_date, \'%d/%m/%Y à %Hh%imin%ss\') AS creation_date FROM posts ORDER BY creation_date DESC LIMIT 0, 5');
    return $req;
}
// affiche le dernier post
function getPost($postId)
{
    $db = dbConnect();
    $req = $db->prepare('SELECT id, title, content, DATE_FORMAT(creation_date, \'%d/%m/%Y à %Hh%imin%ss\') AS creation_date FROM posts WHERE id = ?');
    $req->execute(array($postId));
    $post = $req->fetch();

    return $post;
}
// affiche les commentaires
function getComments($postId)
{
    $db = dbConnect();
    $comments = $db->prepare('SELECT id, author, comment, DATE_FORMAT(comment_date, \'%d/%m/%Y à %Hh%imin%ss\') AS comment_date FROM comments WHERE post_id = ? ORDER BY comment_date DESC');
    $comments->execute(array($postId));

    return $comments;
}

// Nouvelle fonciton qui nous permet d'éviter de répéter du code dans chaque fonction


    function dbConnect()
    {
        $db = new PDO('mysql:host=localhost;dbname=blog_maxime;charset=utf8', 'root', 'root');
        return $db;
    }

// ajouter des commentaires

function postComment($postId, $author, $comment)
{
    $db = dbConnect();
    $comments = $db->prepare('INSERT INTO comments(post_id, author, comment, comment_date) VALUES(?, ?, ?, NOW())');
    $affectedLines = $comments->execute(array($postId, $author, $comment));

    return $affectedLines; 
}

Voici ma class CommentManager.php

<?php


require_once("C:\laragon\www\p5\model\Manager.php");

class CommentManager extends Manager // Héritage = Manager.php
{
   
    public function getComments($postId)
    {
        $db = $this->dbConnect();
        $comments = $db->prepare('SELECT id, author, comment, DATE_FORMAT(comment_date, \'%d/%m/%Y à %Hh%imin%ss\') AS comment_date FROM comments WHERE post_id = ? ORDER BY comment_date DESC');
        $comments->execute(array($postId));

        return $comments;
    }

    public function getComment($commentId)
    {
        $db = $this->dbConnect();
        $comments = $db->prepare('SELECT id, author, comment, DATE_FORMAT(comment_date, \'%d/%m/%Y à %Hh%imin%ss\') AS comment_date FROM comments WHERE id = ? ORDER BY comment_date DESC');
        $comments->execute(array($commentId));
        $data = $comments->fetch();
        return $data;
    }    

    public function postComment($postId, $author, $comment)
    {
        $db = $this->dbConnect();
        $comments = $db->prepare('INSERT INTO comments(post_id, author, comment, comment_date) VALUES(?, ?, ?, NOW())');
        $affectedLines = $comments->execute(array($postId, $author, $comment));

        return $affectedLines;
    }

    public function changeComment($postId, $author, $comment, $commentId){

        $db = $this->dbConnect();
        $comment = $db->prepare("UPDATE comments SET author = ?, comment = ?, comment_date = NOW() WHERE id = ? AND post_id = ?");
  
        $affectedComment = $comment->execute(array($author, $comment, $commentId, $postId));
  
        return $affectedComment;
  
  
    } 
    
}

Voici ma vue viewComment.php

<?php ob_start(); ?>
<h1>Mon super blog !</h1>
<p><a href="index.php">Retour</a></p>

<form action="index.php?action=updateComment&amp;id=<?= $postId["id"]?>&comment_id=<?= $comments['id']?>" method="post">
    
    <div id = "container">
        <div id = "titleform">Modifier le commentaire</div>

            <label for="author">Auteur</label><br />
                <input type="text" id="author" name="author" />
                    
            <label for="comment">Commentaire</label><br />
                <textarea id="comment" name="comment"></textarea>

        <input type="submit" />

    </div>

</form>

<?php $content = ob_get_clean(); ?>

<?php require('C:\laragon\www\p5\view\frontend\template.php'); ?>

Et voici le lien permettant d’accéder au formulaire de modification du commentaire

        while ($comment = $comments->fetch())
        {
        ?>
            <p><strong id="author"><?= htmlspecialchars($comment['author']) ?></strong><div id="date"> le <?= $comment['comment_date'] ?></div>
                <a href="index.php?action=viewComment&amp;id=<?= $comment['id'] ?>">(Modifier)</a>
            <div id="comment"><p><?= nl2br(htmlspecialchars($comment['comment'])) ?></p></div>

Je remercie ceux qui donneront un peu de leur temps pour m’aiguiller, bonne journée à tous !

+0 -0
Connectez-vous pour pouvoir poster un message.
Connexion

Pas encore membre ?

Créez un compte en une minute pour profiter pleinement de toutes les fonctionnalités de Zeste de Savoir. Ici, tout est gratuit et sans publicité.
Créer un compte