我正在尝试学习PHP的MVC架构。所以我玩一些简单的类和函数。我找不到这段代码有什么问题,它返回一个:
致命错误:在非对象中调用成员函数fetch() /opt/lampp/htdocs/test/MVC/Vue.php on 第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();
感谢您的帮助。
答案 0 :(得分:3)
为了扩展Robin的答案,$ stmt-&gt; execute()的返回值是一个布尔值,表示语句是否成功执行。
另外请注意,如果您正在进行面向对象的编程,则应设置PDO :: ERRMODE设置,以便在语句失败时抛出异常:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
答案 1 :(得分: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;