2010-08-29 36 views
0

我正在嘗試學習PHP的MVC體系結構。所以我玩一些簡單的類和功能。我找不到什麼不對的代碼,它返回一個:
有關PHP和MVC的初級問題

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

這裏是我的代碼:

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->preparedQuery->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> 
      <?} 
     } 
} 

和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(); 

感謝您的幫助。

回答

1

你誤解在PDO準備語句,在類新聞,關掉這個:

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

...這個...

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

謝謝。其實,我的問題很愚蠢。 – Coronier 2010-08-29 13:39:08

+0

有點高興我停止使用PHP ......我討厭'$ this->'垃圾。 – mpen 2010-09-29 06:25:34

3

要在羅賓的答案擴大, $ stmt-> execute()的返回值是一個布爾值,指示語句是否成功執行。

在另一方面,如果你正在做面向對象編程,你應該設置PDO :: ERRMODE設置,所以當報表失敗異常將會被拋出:

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

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