Bonjour,

Voila je rencontre un petit problème avec mon code.

Ce que je fais

class Comments{

private $pdo;
private $default = array(
    'username_error' => "Vous n'avez pas rentré de pseudo",
    'email_error' => "Votre email n'est pas valide",
    'content_error' => "Vous n'avez pas mis de message",
    'parent_error' => "Vous essazer de répondre à un commentaire qui n'existe pas"
);
public $errors = array();
public $count  = 0;

/**
 * Permet d'initialiser le module commentaire
 * @param PDO $pdo instance d'une connection mysql via pdo
 * @param array $options
 */
public function __construct($pdo, $options = []) {
    $this->pdo = $pdo;
    $this->options = array_merge($this->default, $options);
}

/**
 * Permet de récupérer les derniers commentaires d'un sujet
 * @param  string $ref
 * @param  integer $ref_id
 * @return array
 */
public function findAll($ref, $ref_id) {
    $q = $this->pdo->prepare("
        SELECT *
        FROM comments2
        WHERE ref_id = :ref_id
            AND ref = :ref
        ORDER BY created DESC");
    $q->execute(['ref' => $ref, 'ref_id' => $ref_id]);
    $comments = $q->fetchAll();
    $this->count = count($comments);

    // Filtrage des réponses
    $replies  = [];
    foreach($comments as $k => $comment){
        if ($comment->parent_id){
            $replies[$comment->parent_id][] = $comment;
            unset($comments[$k]);
        }
    }
    foreach($comments as $k => $comment){
        if (isset($replies[$comment->id])) {
            $r = $replies[$comment->id];
            usort($r, [$this,'sortReplies']);
            $comments[$k]->replies = $r;
        }else{
            $comments[$k]->replies = [];
        }
    }
    return $comments;
}

public function sortReplies($a, $b){
    $atime = strtotime($a->created);
    $btime = strtotime($b->created);
    return $btime > $atime ? -1 : 1;
}

/**
 * Permet de sauvegarder un commentaire
 * @param  string $ref
 * @param  integer $ref_id
 * @return boolean
 */
public function save($ref, $ref_id) {
    $errors = [];
    if (empty($_POST['username'])) {
        $errors['username'] = $this->options['username_error'];
    }
    if (
        empty($_POST['email']) ||
        !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = $this->options['email_error'];
    }
    if (empty($_POST['content'])) {
        $errors['content'] = $this->options['content_error'];
    }
    if (count($errors) > 0) {
        $this->errors = $errors;
        return false;
    }
    if (!empty($_POST['parent_id'])) {
        $q = $this->pdo->prepare("SELECT id
            FROM comments2
            WHERE ref = :ref AND ref_id = :ref_id AND id = :id AND parent_id = 0");
        $q->execute([
            'ref' => $ref,
            'ref_id' => $ref_id,
            'id' => $_POST['parent_id']
        ]);
        if($q->rowCount() <= 0){
            $this->errors['parent'] = $this->options['parent_error'];
            return false;
        }
    }
    $q = $this->pdo->prepare("INSERT INTO comments2 SET
        username = :username,
        email    = :email,
        content  = :content,
        ref_id   = :ref_id,
        ref      = :ref,
        created  = :created,
        parent_id= :parent_id");
    $data = [
        'username' => $_POST['username'],
        'email'    => $_POST['email'],
        'content'  => $_POST['content'],
        'parent_id'=> $_POST['parent_id'],
        'ref_id'   => $ref_id,
        'ref'      => $ref,
        'created'  => date('Y-m-d H:i:s')
    ];
    return $q->execute($data);
}

}

<div class="comment row" style="background: #f2f4f5;
    padding: 1rem;
    border-radius: 0;margin-bottom: 1rem!important;">
  <div class="text-center">
                    <img class="mr-3 rounded-circle" src="../img/avatar.png" width="100" height="100">
                    <h6 class="mt-1 mb-0 mr-3"><?= htmlentities($comment->username); ?></h6>
                  </div>
      <div class="media-body">
        <p class="mt-3 mb-2"><?= htmlentities($comment->content); ?></p>
        <time class="timeago text-muted" datetime="2017-11-05 20:00"><?= date('d/m/Y', strtotime($comment->created)); ?></time>
            <a class="reply"href="#" style="float: right!important;" data-id="<?= $comment->parent_id ? $comment->parent_id : $comment->id; ?>"><span class="fa fa-reply"></span> Reply</a>
    </div>
</div>

Ce que je veux

https://linkpix.fr/u.php?i=5c631fa5cbdbb8964.png

Ce que j'obtiens

https://linkpix.fr/u.php?i=5c6320f78abec706.png
merci d'avance

9 réponses


Lartak
Réponse acceptée

Il te faut inclure les réponses dans la balise ayant la classe media-body du commentaire et non les inclure après avoir fermé celle-ci.

Bonjour.
Tu es sûr que ton problème concerne le PHP et non le HTML/CSS ?
Car les liens que tu nous fournies relatent un problème de présentation des commentaires, par conséquent en relation avec le HTML/CSS.

oui je sais mais pour moi il y doit y avoir une partis php mais en realite je ne sais pas trop comment faire parce que dans ce que je voudrais le commentaires parent et enfants sont ensemble alors que sur ma page a moi il y a une separation donc peut etre qu´il faut faire une indication en php

Ton problème vient très certainement de ton code html/css, sois tu as mal placé tes balises pour les commentaires imbriqués, sois tu la mal codé.

Montres nous ton code complet HTML/PHP, car dans le code que tu nous montre il n'y a aucune boucle, alors que tu dois avoir deux boucles, une qui boucle sur les commentaires et la seconde sur les réponses à ses commentaires.
Donc quelque chose qui devrait resembler à ceci :

<?php foreach ($comments as $comment): ?>
  <div class="comment row" style="background: #f2f4f5; padding: 1rem; border-radius: 0;margin-bottom: 1rem!important;">
      <div class="text-center">
          <img class="mr-3 rounded-circle" src="../img/avatar.png" width="100" height="100">
          <h6 class="mt-1 mb-0 mr-3"><?= htmlentities($comment->username); ?></h6>
      </div>
      <div class="media-body">
          <p class="mt-3 mb-2"><?= htmlentities($comment->content); ?></p>
          <time class="timeago text-muted" datetime="<?= $comment->created ?>"><?= date('d/m/Y', strtotime($comment->created)); ?></time>
          <a class="reply"href="#" style="float: right!important;" data-id="<?= $comment->parent_id ? $comment->parent_id : $comment->id; ?>">
          <span class="fa fa-reply"></span> Reply</a>
      </div>
      <?php if (!empty($comment->replies): foreach ($comment->replies as $reply): ?>
          <!-- Code HTML/PHP pour l'affichage d'une réponse -->
      <?php endforeach; endif; ?>
  </div>
<?php endforeach; ?>

d'accord j'ai trouvé du coup
j'ai fait ceci

 <?php foreach ($comments as $comment): ?>
          <div class="comment row media mb-3">
            <div class="text-center">
                              <img class="mr-3 rounded-circle" src="../img/avatar.png" width="100" height="100">
                              <h6 class="mt-1 mb-0 mr-3"><?= htmlentities($comment->username); ?></h6>
                            </div>
                <div class="media-body">
                  <p class="mt-3 mb-2"><?= htmlentities($comment->content); ?></p>
                  <time class="text-muted"><?= date('d/m/Y', strtotime($comment->created)); ?></time>
                      <a class="reply"href="#" style="float: right!important;" data-id="<?= $comment->parent_id ? $comment->parent_id : $comment->id; ?>"><span class="fa fa-reply"></span> Répondre</a>
                    </div>
</div>
            <?php foreach ($comment->replies as $comment): ?>
              <div class="media mt-3">
                  <div class="pr-3 text-center">
                    <img class="mr-3 rounded-circle" src="../img/avatar.png" alt="John" width="100" height="100">
                    <h6 class="mt-1 mb-0 mr-3"><?= htmlentities($comment->username); ?></h6>
                  </div>
                  <div class="media-body">
                    <p class="mt-3 mb-2"><?= htmlentities($comment->content); ?></p>
                    <time class="text-muted"><?= date('d/m/Y', strtotime($comment->created)); ?></time>
                    <a class="reply"href="#" style="float: right!important;" data-id="<?= $comment->parent_id ? $comment->parent_id : $comment->id; ?>"><span class="fa fa-reply"></span> Répondre</a>
                  </div>
</div>
            <?php endforeach ?>
        <?php endforeach ?>

mais maintenant ça me fait cela https://linkpix.fr/u.php?i=5c63f5cdee0e3194.png

C'est clairement un problème d'organisation de ton html, tu peut nous montrer le code html de l'image ou le rendu était bon

le voici

<h3>4 comments</h3>

              <div class="media mb-3">
                <div class="text-center">
                  <img class="mr-3 rounded-circle" src="img/avatars/3.png" alt="Lucy" width="100" height="100">
                  <h6 class="mt-1 mb-0 mr-3">Lucy</h6>
                </div>
                <div class="media-body">
                  <p class="mt-3 mb-2">Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.</p>
                  <time class="timeago text-muted" datetime="2017-12-03 20:00">3 december 2017</time>
                  <a class="float-right" href="#"><span class="fa fa-reply"></span> Reply</a>

                  <div class="media mt-3">
                    <div class="pr-3 text-center">
                      <img class="mr-3 rounded-circle" src="img/avatars/2.png" alt="John" width="100" height="100">
                      <h6 class="mt-1 mb-0 mr-3">John</h6>
                    </div>
                    <div class="media-body">
                      <p class="mt-3 mb-2">Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.</p>
                      <time class="timeago text-muted" datetime="2017-12-14 19:00">14 december 2017</time>
                      <a class="float-right" href="#"><span class="fa fa-reply"></span> Reply</a>
                    </div>
                  </div>
                </div>
              </div>

              <div class="media mb-3">
                <div class="text-center">
                  <img class="mr-3 rounded-circle" src="img/avatars/1.png" alt="Kim" width="100" height="100">
                  <h6 class="mt-1 mb-0 mr-3">Kim</h6>
                </div>
                <div class="media-body">
                  <p class="mt-3 mb-2">Vestibulum volutpat pretium libero. Cras id dui. Aenean ut eros et nisl sagittis vestibulum. Nullam nulla eros, ultricies sit amet, nonummy id, imperdiet feugiat, pede. Sed lectus. Donec mollis hendrerit risus. Phasellus nec sem in justo pellentesque facilisis.</p>
                  <time class="timeago text-muted" datetime="2017-11-20 20:00">20 november 2017</time>
                  <a class="float-right" href="#"><span class="fa fa-reply"></span> Reply</a>
                </div>
              </div>

              <div class="media mb-3">
                <div class="text-center">
                  <img class="mr-3 rounded-circle" src="img/avatars/4.png" alt="Paula" width="100" height="100">
                  <h6 class="mt-1 mb-0 mr-3">Paula</h6>
                </div>
                <div class="media-body">
                  <p class="mt-3 mb-2">Nam pretium turpis et arcu. Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris. Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris. Praesent adipiscing. Phasellus ullamcorper ipsum rutrum nunc. Nunc nonummy metus.</p>
                  <time class="timeago text-muted" datetime="2017-11-05 20:00">5 november 2017</time>
                  <a class="float-right" href="#"><span class="fa fa-reply"></span> Reply</a>
                </div>
              </div>

Merci beaucoup pour votre temps et surtout votre aide