PHP foreach MVC 警告

PHP foreach MVC Warning

我一直在努力学习一些 PHP。我正在尝试打印出我的数据库的内容。我一直在学习教程,但 运行 收到以下警告,我根本无法移动。

警告

Warning: Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/Lab10/app/views/View.php on line 20

Foreach 循环

$HTMLItemList = "";
foreach ( $this->model->itemList as $row ) 
    $HTMLItemList .= "<li><strong>" . $row ["title"] . ": </strong>" . $row ["price"] . "<blockquote>" . $row ["description"] . "</blockquote></li>";
$HTMLItemList = "<ul>" . $HTMLItemList . "</ul>";

模型->itemList

public$itemList=null;
public function prepareItemList () {
    $this->ItemList = $this->itemsDAO->getItems ();
}

itemsDAO->getItems()

public function getItems () {
    $sqlQuery = "SELECT *";
    $sqlQuery .= "FROM items";
    $sqlQuery .= "ORDER BY items.title;";

    $result = $this->getDbManager () -> executeSelectQuery ( $sqlQuery );
    return $result;
}

PHP 试图在 foreach 上迭代的变量不是数组。尝试var_dump()它来检查。

您可以将 array() 设置为模型上 itemList 属性的默认值,这样如果您的初始化方法未被调用,您的 foreach 将不会发出警告。

您在此处犯的错误 是调用了您的 getItems 方法并将结果放在 ItemList 属性而不是 itemList 上。请注意!

只需更换

public function prepareItemList() {
  $this->ItemList = $this->itemsDAO->getItems();
}

来自

public function prepareItemList() {
  $this->itemList = $this->itemsDAO->getItems();
}

它会起作用。

请试试这个

$this->model->prepareItemList();
$HTMLItemList = "";
foreach ( $this->model->itemList as $row ) 
   $HTMLItemList .= "<li><strong>" . $row ["title"] . ": </strong>" . $row ["price"] . "<blockquote>" . $row ["description"] . "</blockquote></li>";

public $itemList=null;
public function prepareItemList () {
    $this->itemList = $this->itemsDAO->getItems ();
}