我试图从数据库中得出结论,我使用 PDO 连接到它,我尝试通过循环得出结论while,当我调用函数时,出现fetch()错误:
致命错误:在第 24 行的 /home/s/ser588nn/shop.ser588nn.beget.tech/public_html/models/News.php 中的布尔值上调用成员函数 fetch()
最有可能的是,当请求被执行时,它会query返回false,尽管请求正确地检查了所有内容。
模型 :
public static function getNewsList()
{
//Запрос к БД
$host = '127.0.0.1';
$dbname = 'ser588nn_shop';
$user = 'ser588nn_shop';
$password = 'rootroot';
$db = new PDO("mysql:host = $host;dbname = $dbname",$user, $password);
$newsList = array();
$result = $db->query('SELECT id, title, date, short_content FROM news ORDER BY date LIMIT 10');
$i = 0;
while($row = $result->fetch()) {
$newsList[$i]['id'] = $row['id'];
$newsList[$i]['title'] = $row['title'];
$newsList[$i]['date'] = $row['date'];
$newsList[$i]['short_content'] = $row['short_content'];
$i++;
}
return $newsList;
}
}
?>
控制器:
<?php
include_once ROOT. '/models/News.php';
class NewsController {
public function actionIndex()
{
$newsList = array();
$newsList = News::getNewsList();
echo "<pre>";
print_r($newsList);
echo "</pre>";
return true;
}
public function actionView($id)
{
echo "Список одной новости";
return true;
}
}
?>
PDO 不是一个愚蠢的 mysql_query,你不需要手动弄乱来获取一个数组。