开发者

Beginnner question about PHP and MVC

开发者 https://www.devze.com 2023-01-13 19:40 出处:网络
I\'m trying to learn MVC architecture for PHP. So I play with some simple classes and functions. I can\'t find what\'s wrong with this code, which returns a:

I'm trying to learn MVC architecture for PHP. So I play with some simple classes and functions. I can't find what's wrong with this code, which returns a:

Fatal error: Call to a member function fetch() on a non-object in /opt/lampp/htdocs/test/MVC/Vue.php on line 15

Here's my code:

Model.php:

class News {
    public function ConnBdd() {
        $this->bdd = new PDO('mysql:host=localhost;dbname=db301591273', 'root', '');
        $this->query = "SELECT Nom,IdTest,Image,DATE_FORMAT(DateCreation, '%Y-%m-%d') AS DateCreation FROM Questionnaires WHERE autorise='1' ORDER BY DateCreation DESC LIMIT 0, 4";
        $this->preparedQuery = $this->bdd->prepare($this->query);
        $this->executedQuery = $this->preparedQ开发者_Go百科uery->execute();
    }
 }

Controller.php

class Controller {
    public $Model;
    public $View;
    public $News;
    public function ShowNews(){
        $this->News->ConnBdd();
        $this->View->ShowDaNews();
    }
}

View.php

class View {
    public $Model;
    public $News;

    public function ShowDaNews() {
        while ($c = $this->News->executedQuery->fetch()) {?>
    <tr>
    <td class="tableImg"><?echo '<img src="/img/ico/'.$tests['Image'].'.png" />'?></td>
    <td class="tableTest"><?echo '<a href="/page/php?t='.$tests['IdTest'].'">'.$tests['Nom'].'</a>'?></td>
    </tr>
            <?}
       }
}

and Index.php

require_once 'Modele.php';
require_once 'Controleur.php';
require_once 'Vue.php';

$Model= new Model();
$Controller = new Controller();
$View = new View();
$Controller->Model = $Model;
$Controller->View = $View;
$News = new News();
$Controller->News = $News;
$View->News = $News;
$Controller->ShowNews();

Thanks for your help.


To expand on Robin's answer, the return value of $stmt->execute() is a boolean, indicating whether the statement executed successfully.

On another note, if you're doing object-oriented programming, you should set the PDO::ERRMODE setting, so that when statements fail exceptions will be thrown:

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

See http://php.net/manual/en/pdo.setattribute.php


You've misunderstood prepared statements in PDO, in the class News, switch this:

$this->preparedQuery = $this->bdd->prepare($this->query);
$this->executedQuery = $this->preparedQuery->execute();

...to this...

$this->preparedQuery = $this->bdd->prepare($this->query);
$this->preparedQuery->execute();
$this->executedQuery = $this->preparedQuery;
0

精彩评论

暂无评论...
验证码 换一张
取 消