Système de likes et de dislikes

Par Batfire le 30 Apr 2019 1 +99

Bonjour Clouder je reviens vers vous après quelques mois car je ne trouve toujours pas la solution à mon problème.

En effet je souhaiterais ajouter un système de like et dislike sur mon site.(wizung.com)

Lorsque je clique sur like tous les posts sont likés alors que je voudrais qu'un seul post soit liké a la fois.

Avez-vous une idée du problème ?

Cordialement

//page home.php

<?php
session_start();

    include('config/connexionDB.php');

    if (!isset($_SESSION['id'])){
        header('Location: index.php');
        exit;
    }

    $my_id = $_SESSION['id'];

    // On récupère les informations de l'utilisateur connecté
    $req = $DB->query("SELECT *
        FROM posts
        LEFT JOIN followers ON followers.id_following = posts.user_id
        LEFT JOIN users ON users.id = posts.user_id
        WHERE followers.id_follower = '$my_id'
        ORDER BY post_date_creation DESC");

    $req = $req->fetchAll();

   $fo = $DB->query("SELECT *
    FROM likes
    WHERE id_user = ?",
    array($_SESSION['id']));

   $fo = $fo->fetch();

?>
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="author" content="The Wizung team">
    <link rel="icon" href="images/Wizung.svg">

    <title>Wizung</title>

    <!-- Bootstrap core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Home CSS -->
    <link href="css/home.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="navbar-top.css" rel="stylesheet">
    <script type="text/javascript">
    <!--
        var timeout = setTimeout(
        function() {
            document.getElementById('welcome').innerHTML = null;
            clearTimeout(timeout);
            }
        ,5000); // temps en millisecondes
    </script>
  </head>

  <body>

    <nav class="navbar navbar-expand-md navbar-light bg-light mb-4">
      <a class="navbar-brand" href="home">Home</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarCollapse">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item">
            <a class="nav-link" style="font-size: large" href="profile">Profile</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" style="font-size: large" href="followers">followers</a>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" style="font-size: large" href="logout" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Logout</a>
            <div class="dropdown-menu" aria-labelledby="dropdown01">
              <a class="dropdown-item" href="logout">Logout</a>
            </div>
          </li>
        </ul>
        <form method="get" action="search_user.php" class="form-inline mt-2 mt-md-0">
          <input class="form-control mr-sm-2" type="text" name="contenu" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-primary my-2 my-sm-0" name="search" type="submit">Search</button>
        </form>
      </div>
    </nav>
    <div id="welcome">
     <div class="alert alert-primary" align="center"><?php echo 'Bienvenue ' . $_SESSION['firstname'] . ' !'; ?></div>
    </div>
    <main role="main" class="container">
      <div class="jumbotron" style="border-radius: 25px;">
        <form method="post" enctype="multipart/form-data" action="post.php">
          <textarea class="form-control" name="content" placeholder="Post what you want..." required></textarea><br>
          <div class="input-group mb-3">
           <div class="custom-file">
             <input type="file" class="custom-file-input" name='file' id="inputGroupFile01" aria-describedby="inputGroupFileAddon01" multiple>
             <label class="custom-file-label" for="inputGroupFile01">File</label>
           </div>
          </div>
          <button class="btn btn-primary" style="border-radius: 10px" type="submit" name="post">Post</button>
        </form>
      </div>
<?php
    foreach($req as $r){

        $info = new SplFileInfo($r['fileNameNew']);

        $extaudio = array('mp3', 'flac');

        $extvideo = array('mp4', 'AVI');

        $extimage = array('png', 'jpg');

        //display image

        if(in_array($info->getExtension(), $extimage)){

        ?>
             <div class="card" style="max-width: 46rem;">
                 <div class="card-body" align="center">
                     <div class="post-information">
                      <div align="left">
                       <?php
                           if (file_exists("public/avatars/".$r['user_id'] . "/" . $r['avatar']) && isset($r['avatar'])) {
                       ?>
                           <img style='border-radius: 35px;' src="<?= "public/avatars/". $r['user_id'] . "/" . $r['avatar']; ?>" width="65" class="sz-image"/>
                       <?php
                           }else{
                       ?>
                           <img style='border-radius: 35px;' src="public/avatars/defaults/default.png" width="65" class="sz-image"/>
                       <?php
                           }
                       ?>
                       <a href="see_profile.php?id=<?= $r['user_id'] ?>"><?= $r['author'] ?></a>
                      </div>
                      <div align="right">
                       <h6><?= $r['post_date_creation'] ?></h6>
                      </div>
                     </div>
                     <?php echo"<img class='card-img-top' style='border-radius: 20px;' src='uploads/".$r['fileNameNew']."' >"; ?>
                     <h5><?= $r['content'] ?></h5>
                     <?php
                      if (isset($fo['id_user'])) {
                     ?>
                     <a class="btn btn-danger" href="unlike.php?post_id=<?= $r['user_id'] ?>">UnLike</a>
                     <?php
                      }else{
                     ?>
                     <a class="btn btn-primary" href="like.php?post_id=<?= $r['user_id'] ?>">Like</a>
                     <?php
                      }
                     ?>
                 </div>
             </div><br>
        <?php

        //display audio file

        }elseif(in_array($info->getExtension(), $extaudio)){
        ?>
             <div class="card" style="max-width: 46rem;">
                 <div class="card-body" align="center">
                     <div align="left">
                      <?php
                          if (file_exists("public/avatars/".$r['user_id'] . "/" . $r['avatar']) && isset($r['avatar'])) {
                      ?>
                          <img style='border-radius: 35px;' src="<?= "public/avatars/". $r['user_id'] . "/" . $r['avatar']; ?>" width="65" class="sz-image"/>
                      <?php
                          }else{
                      ?>
                          <img style='border-radius: 35px;' src="public/avatars/defaults/default.png" width="65" class="sz-image"/>
                      <?php
                          }
                      ?>
                      <a href="see_profile.php?id=<?= $r['user_id'] ?>"><?= $r['author'] ?></a>
                     </div>
                     <h5><?= $r['content'] ?></h5>
                     <div>
                     <?php echo "<audio style='border-radius: 20px;' src='uploads/".$r['fileNameNew']."'controls>"; ?>
                     </div>
                 </div>
             </div><br>
         <?php

         //display video file

        }elseif(in_array($info->getExtension(), $extvideo)){
        ?>
             <div class="card" style="max-width: 46rem;">
                 <div class="card-body" align="center">
                     <div align="left">
                      <?php
                          if (file_exists("public/avatars/".$r['user_id'] . "/" . $r['avatar']) && isset($r['avatar'])) {
                      ?>
                          <img style='border-radius: 35px;' src="<?= "public/avatars/". $r['user_id'] . "/" . $r['avatar']; ?>" width="65" class="sz-image"/>
                      <?php
                          }else{
                      ?>
                          <img style='border-radius: 35px;' src="public/avatars/defaults/default.png" width="65" class="sz-image"/>
                      <?php
        &								
Cette pub permet au site de vivre ...

1 Commentaire

Salut Batfire 🙂


Pour ton système de like et de dislike je peux te donner une piste car la tu m'as donné un bout de code 😅


Alors si tu affiches un article avec le nombre de like et de dislike il faut que tu mettes un code comme ceci :


 $fo_like = $DB->query("SELECT COUNT(DISTINCT like) AS like
    FROM likes
    WHERE id_post = ?
    GROUP BY like",
    array($see_post['id']));

$fo_like = $fo_like->fetch(); 

$fo_dislike = $DB->query("SELECT COUNT(DISTINCT dislike) AS dislike
   FROM likes
   WHERE id_post = ?
   GROUP BY dislike",
   array($see_post['id']));

$fo_dislike = $fo_dislike->fetch(); 


Comme ça tu récupères le nombre de like et de dislike de ton post.


Ensuite pour comptabiliser l'action de ton utilisateur tu fais comme cela :


<form method="post">
  ...
  <input type="submit" name="is_like" value="like (ou ton icône)"/><input type="submit" name="is_dislike" value="like (ou ton icône)"/>
  ...
form>


et pour le PHP :


<?php
  if(isset($_POST['is_like'])){
    $is_like = (int) $is_like; // (int) pour être sûr d'avoir qu'un entier
    
    $verif_like = array(0, 1);

    if(!in_array($is_like, $verif_like)){
      $valid = false;
      $err_like = "...";
    }

    if($valid){
      $DB->insert("INSERT INTO like (id_post, id_user, is_like, is_dislike) VALUES (?, ?, ?, ?)",
        array($see_post['id'], $_SESSION['id'], 1, 0));
    }
  }elseif(isset($_POST['is_like'])){
    $is_diske = (int) $is_like;

    $verif_dislike = array(0, 1);

    if(!in_array($is_like, $verif_dislike )){
      $valid = false;
      $err_dislike = "...";
    }
    
    if($valid){
      $DB->insert("INSERT INTO like (id_post, id_user, is_like, is_dislike) VALUES (?, ?, ?, ?)",
        array($see_post['id'], $_SESSION['id'], 0, 1));
    }
  }
?>


Les points à améliorer seraient :

  • Vérifier si l'utilisateur à déjà oui ou non liker ou disliker pour changer son vote et de mettre un UPDATE et non pas un INSERT,
  • Que l'utilisateur puisse voir s'il a déjà like ou non
Cette pub permet au site de vivre ...