【问题标题】:Invalid argument supplied for foreach(), Cant find why为 foreach() 提供的参数无效,找不到原因
【发布时间】:2011-07-13 09:27:35
【问题描述】:

我是初级 php 程序员。我试图使用 MVC,但我什至无法通过这个测试。

问题:警告:在 httpdocs/data/serieDAO.php 第 15 行为 foreach() 提供的参数无效

谁能告诉我是什么导致了这个问题?

代码(很长见谅):

/index.php

<?php 
ini_set('display_errors', 1);
// main controller
require_once ("business/serieservice.php");
$service = new SerieService();
$serielijst = $service->toonAlleSeries();
include("test/test1.php");
?>

/business/serieservice.php

<?php
require_once("data/serieDAO.php");
class SerieService{

    public function toonAlleSeries(){
        $serieDAO = new SerieDAO();
        $lijst = $serieDAO->displayList();
        return $lijst;
    }
}
?>

/data/serieDAO.php

 <?php
require_once("entities/series.class.php");

class SerieDAO{

    // public function __construct(){
        // $dbh = new PDO("mysql:host=localhost;dbname=tvseasons", "seasons", "bompa");
    // }

    public function displayList(){
        $list = array();
        $dbh = new PDO("mysql:host=localhost;dbname=tvseasons", "seasons", "bompa");
        $sql = "select id, title, desc, url, genre, trailer from Series";
        $resultSet = $dbh->query($sql);
        foreach ($resultSet as $row){
            $serie = new Series($row["id"], $row["title"],$row["desc"], $row["url"], $row["genre"], $row["trailer"]);
            array_push($list, $serie);
        }
        $dbh = null;        
        return $list;
    }


}
?>

/entities/series.class.php

<?
//class met getters en setters van series entity
class Series{
  private $id;
  private $title;
  private $desc; //description
  private $url;
  private $genre;
  private $trailer;

  /* Try to figure out how to determine the $id. Cannot be set obviosly but get should be possible */

  //setters
  function setTitle ($title){
    $this->title = $title;
  }
  function setDesc($desc){
    $this->desc = $desc;
  }
  function setUrl($url){
    $this->url = $url;
  }
  function setGenre($genre){
    $this->genre = $genre;
  }
  function setTrailer($trailer){
    $this->trailer = $trailer;
  }

  //getters
  function getTitle(){
    return $this->title;
  }
  function getDesc(){
    return $this->desc;
  }
    function getUrl(){
    return $this->url;
  }
    function getGenre(){
    return $this->genre;
  }
    function getTrailer(){
    return $this->trailer;
  }
}
?>

/test/test1.php

<html>
<head>
<title>Test1 lijst series</title>
</head>
<body>
<h1>Een lijst van alle series</h1>
<ul>
<?php
foreach($serielijst as $serie){
 print ("<li>bla bla</li>");
}
?>
</ul>
</body>
</html>

编辑:我知道 foreach 中的代码还没有工作。但我已经发现这不是原因。

【问题讨论】:

  • 您是否检查过您是否从数据库查询中获得任何结果? Foreach 期待一个数组,它没有得到它。检查数组的创建位置以及可能失败的位置。
  • 在创建 PDO 对象时使用 try/catch,因此您可以看到引发的任何异常。也尝试只发布代码的相关部分。
  • 转至php.net/manual/en/function.mysql-query.php 以获取有关错误检查的信息。就像他们说的那样,确保你的查询确实返回了一些东西。
  • 回到我还在做 php 的时候,我这样做是为了从每一行中获取值 while ($row = mysql_fetch_assoc($result)) { echo $row['firstname'];回声 $row['姓氏'];回声 $row['地址'];回声 $row['年龄']; }
  • @Jarco 考虑将您的代码缩减为您能想到的最小的非工作示例,以解决您的下一个问题。实际上强迫人们阅读 100 行代码,其中 96 行与问题无关,这不仅是不礼貌的,而且将代码减少到有问题的部分有助于理解问题和其他人 重现它。

标签: php foreach


【解决方案1】:

您的查询未能返回带有结果集的数组,因为您为其中一个表列使用了保留字 (desc)。

变化:

$sql = "select id, title, desc, url, genre, trailer from Series";

到:

$sql = "select id, title, `desc`, url, genre, trailer from Series";

【讨论】:

  • 我刚刚通过在 phpmyadmin 中运行查询也发现了这一点。修复它的好技巧。谢谢
【解决方案2】:

该错误通常意味着 foreach 的参数不是数组或空数组。您可以尝试通过var_dump($resultSet) 查看 $resultSet 的内容。我猜你从 MySQL 得到一个空的回复,这导致了这个错误。要验证这一点,您应该尝试手动运行查询。

【讨论】:

  • 我已经手动完成了。你是正确的,错误就在那里。 desc 在 sql 中保留。我应该知道...
【解决方案3】:

请转储 $resultSet 变量并查看它是否为数组。 Foreach 方法仅排除数组,因此如果提供了其他任何内容,它将引发错误。

【讨论】:

    【解决方案4】:

    似乎连接或查询失败。请尝试以下操作,看看有什么问题:

    if ($resultSet) {
            foreach ($resultSet as $row){
                $serie = new Series($row["id"], $row["title"],$row["desc"], $row["url"], $row["genre"], $row["trailer"]);
                array_push($list, $serie);
            }
    else {
        var_dump($dbh->errorInfo());
    }
    

    【讨论】:

      【解决方案5】:

      可能是 $resultSet 不是数组。 这可能是因为有时查询没有获取数据。

      你应该在 foreach 循环之前添加这个条件

      if(is_array($resultSet) && count($resultSet)>0){

      foreach($resultSet as $row){
      }
      

      }

      【讨论】:

        【解决方案6】:
         $dbh = new PDO("mysql:host=localhost;dbname=tvseasons", "seasons", "bompa"); 
         $sql = "select id, title, desc, url, genre, trailer from Series";
        

        检查这些行,您的连接可能有错误,或检查与您的表格字段匹配的查询。手动检查,是否正在执行选择查询。

        【讨论】:

          【解决方案7】:

          看起来你没有获取 /data/serieDAO.php 中的数据,像这样:

               $resultSet = $dbh->query($sql);
               $rows = $resultSet->fetchAll(PDO::FETCH_ASSOC); // this looks missing in your code
              foreach($rows as $key => $value) {
                  $data_array[$key] = $value;// replace with your "serie" stuffs
              }
          

          【讨论】:

            猜你喜欢
            • 2011-05-17
            • 2011-02-07
            相关资源
            最近更新 更多