0

I am creating a website in php with mvc architecture and I have the following mistake message with the comments part in single.php (view) :

Notice: Trying to get property of non-object in C:\wamp64\www\projet5\P5\Models\Critics.php on line 17, line 29. comments.php on line 3, 4, 8, 16

The code is below. I think the problem is with the query method Ichanged in connection.php. I can't adapt the functions in models at this new query method. Could you give me a clue about what is the problem?

Thanks a lot

Connection.php

<?php require_once 'Config/Config.php';

class Connection {

// Connection
private function getBdd() {
try {
  $bdd = ConfigDB::database();
  $pdo = new PDO("mysql:host={$bdd['host']}; dbname={$bdd['db_name']}",                 "{$bdd['username']}", "{$bdd['password']}");
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
  print "Error!: " . $e->getMessage() . "<br/>";
  die();
}
return $pdo;
}

// Query
public function query($sql, $params = array(), $fetch = null) {
try {
  $req = self::getBdd()->prepare($sql);
  $req->execute($params);

  if ($fetch == 'one') {
    return $req->fetch();
  } else if ($fetch == 'all') {
    return $req->fetchAll();
  } else {
    return $req;
  }

} catch (PDOException $e) {
  print "Error!: " . $e->getMessage() . "<br/>";
  die();
}
}
}

An exemple of a controller :

  public function single() {
if (isset($_GET['id'])) {
  $id = $_GET['id'];
  $movie = $this->Movie->getMovie($id);
  $poster = $this->Movie->getPosterPath($movie['poster_path'], false, 300, 450);
  $cast = $this->Cast;
  $msg = $this->Comment->reportCritic();
  $this->Comment->insertCritic();
  $critics = $this->Comment->findAllWithChildren($_GET['id']);
  $rating = $this->Rating->avg($movie['id']);
  $view = require 'views/single.php';
} else {
  header('Location:index.php?p=404');
}
}

Class comments in models

<?php
require_once 'Connection.php';

class Critics extends Connection{


//Récupère les critiques selon l'id de l'article.

public function findAllById($post_id) {
  $sql = "SELECT *, DATE_FORMAT(date, '%d/%m/%Y à %H:%i') AS date
          FROM critics
          WHERE id_movie = ?";
  $params = [$post_id];
  $comms = $this->query($sql,$params,'all');
  $critics_by_id = [];
  foreach ($comms as $comm) {
      $critics_by_id[$comm->id] = $comm;
  }
  return $critics_by_id;
 }


//Récupèrer les critiques qui ont des enfants.

public function findAllWithChildren($post_id, $unset_children = true) {

$comms = $critics_by_id = $this->findAllById($post_id);
foreach ($comms as $id => $comm) {
    if ($comm->parent_id != 0) {
        $critics_by_id[$comm->parent_id]->children[] = $comm;
        if ($unset_children) {
            unset($comms[$id]);
        }
    }
 }
return $comms;
}


//récupèrer une critique signalée.

public function findCritics() {

$sql = "SELECT *,DATE_FORMAT(date, '%d/%m/%Y à %H:%i') AS date FROM critics WHERE report=1";
$req = $this->query($sql);
return $req;
 }

 public function noCritic() {
 if ($this->findCritics() == false) {
    $msg = '<div class="alert alert-warning">Il n\'y a pas de critiques signalées.</div>';
    return $msg;
 }
 }


 //insérer une critique.
 public function insertCritic(){

  if(isset($_POST['content']) && !empty($_POST['content'])){

    $parent_id = isset($_POST['parent_id']) ? $_POST['parent_id'] : 0;
    $depth = 0;

    if ($parent_id != 0){

      $sql = 'SELECT id, depth  FROM critics WHERE  id = ?';
      $params = [$parent_id];
      $comm = $this->query($sql,$params, 'one');
      if ($comm == false) {
        throw new Exception("Ce parent n'existe pas");
      }
      $depth = $comm->depth + 1;
    }
     if ($depth >= 3) {
       echo "Impossible de rajouter une critique";
     }
     else {
       $sql = 'INSERT INTO critics SET content = ?, author = ?, id_movie = ?, parent_id = ?, date = NOW(), depth = ?';
       $params = array($_POST['content'], $_POST['nom'], $_GET['id'], $parent_id, $depth);
       $req = $this->query($sql,$params);
     }
   }
 }


 //signaler une critique

 public function reportCritic() {
 if (isset($_POST['report'])) {
   $value = $_POST['valeur'];
   $id = $_POST['idval'];
   $sql = 'UPDATE critics SET report = 1 WHERE id_movie =? AND id=?';
   $params = [$value, $id];
   $this->query($sql, $params);
   $msg = '<div class="alert alert-warning alert-signal">La critique a été signalée.</div>';
   return $msg;
 }
 }


 //fonction qui permet d'approuver une critique signalée.

 public function appCritic() {
 if (isset($_POST['ok'])) {
   $idFilm = $_POST['ok'];
   $idCritic = $_POST['idOK'];
   $sql = 'UPDATE critics SET report = 0 WHERE id_movie=? AND id=?';
   $params = [$idFilm, $idCritic];
   $this->query($sql, $params);
   header('Location:index.php?p=dashboard');
 }
 }

 //Fonction qui permet de supprimer une critique signalée.

 public function deleteCritic() {
 if (isset($_POST['trash'])) {
   $idFilm = $_POST['trash'];
   $idCritic = $_POST['idDEL'];
  $sql ='DELETE FROM critics WHERE id=? AND id_movie=?';
  $params = [$idCritic,$idFilm];
  $this->query($sql, $params);
  header('Location:index.php?p=dashboard');
 }
 }

 }

Views

      <div class="Sectioncommentaires" id="commentaires">
    <?php foreach($critics as $critic): ?>
        <?php require('comments.php'); ?>
    <?php endforeach; ?>

comments.php

<div id="comment-<?= $critic->id ?>">
<p>
<b><?= $critic->author ?></b>
<span class="text-muted">le <?= $critic->date ?></span>
</p>
<div class="blockquote">
<blockquote>
  <?= htmlentities($critic->content) ?>
</blockquote>
</div>
<div class="formulaire">
<form class="form-group"  method="post">
  <p class="text-left">
    <input type="hidden" name="valeur" value="<?= $critic->id_movie ?>">
    <input type="hidden" name="idval" value="<?= $critic->id ?>">
    <?php if($critic->depth <= 1): ?>
      <button  type="button" class="reply btn btn-default" data-id="<?= $critic->id ?>"><span class="glyphicon glyphicon-share-alt"></span></button>
    <?php endif; ?>
    <button type="submit" name="signal" class="btn btn-default"><span class="glyphicon glyphicon-warning-sign"></span></button>
  </p>
</form>
</div>
</div>

<div style="margin-left: 50px;">
<?php if(isset($critic->children)): ?>
    <?php foreach($critic->children as $critic): ?>
        <?php require('comments.php'); ?>
    <?php endforeach; ?>
<?php endif; ?>
</div>
tereško
  • 58,060
  • 25
  • 98
  • 150
Cedjag
  • 11
  • 1
  • 4

1 Answers1

-2

$critic is not an object. Perhaps it is an array.

Try $critic['author'] instead.

If that doesn't work, var_dump($critic); exit; to see what the variable actually is.

delboy1978uk
  • 12,118
  • 2
  • 21
  • 39