【问题标题】:foreach() Invalid argument suppliedforeach() 提供的参数无效
【发布时间】:2021-01-21 11:08:21
【问题描述】:

我有这段代码适用于我的朋友,但是当我运行它时,它给出了这个警告:在第 10 行的 C:\wamp64\www\DVD_show.php 中为 foreach() 提供了无效参数

有什么问题?

    '''
    <?php
    try {
        /*** connect to SQLite database ***/
        $dbh = new PDO("sqlite:dvd.db");
    //echo("ok");
    if(isset($_GET['name'])){
    $name=$_GET['name'];
    $sql = "SELECT * FROM DVD where name='".$name."'";
    }else $sql = "SELECT * FROM DVD";
        foreach ($dbh->query($sql) as $row)
            {
            print 'dvds[index++]="#'.$row['name'] ."#".$row['director']. "#".                 $row['price']."#".$row['stock'].'#";<br>';
            //dvds[index++]="#Life is Beautiful#dvd1#10.5#10#history#Roberto Benigni#";
            }
    
        /*** close the database connection ***/
        $dbh = null;
        }
    catch(PDOException $e)
        {
        echo $e->getMessage();
        }
    ?>
    <form action="http://127.0.0.1/DVD_show.php" method="get">
     <p>Please input DVD name: <input type="text" name="name" /></p>
    
     <p><input type="submit" /></p>
    </form>
    '''

【问题讨论】:

    标签: php


    【解决方案1】:

    $dbh-&gt;query($sql) 将返回您Statement。您应该使用fetchfetchAll 来获得结果。虽然fetch 只会返回一个 - 所以不可迭代,您应该使用fetchAll,它总是返回数组。

    【讨论】:

      【解决方案2】:

      dbh-> 查询在这个地方是错误的,因为它只返回一个语句而不是你可以与 foreach 一起使用的东西

      您首先需要使用 fetch() 或 fetchAll() 方法

      请查看更改后的代码。

      注意:如果您有大量结果,则不建议使用 fetchAll,因为它会加载 wohle 数据集。然后更好地使用 fetch() 并且像下面的示例中所示的链接。

        <?php
          try {
              /*** connect to SQLite database ***/
              $dbh = new PDO("sqlite:dvd.db");
          //echo("ok");
          if(isset($_GET['name'])){
          $name=$_GET['name'];
          $sql = "SELECT * FROM DVD where name='".$name."'";
          }else $sql = "SELECT * FROM DVD";
          
      //change this 
          
      $data =  $dbh->query($sql) ->fetchAll();
              foreach ($data as $row)
      
      //changes end 
                  {
                  print 'dvds[index++]="#'.$row['name'] ."#".$row['director']. "#".                 $row['price']."#".$row['stock'].'#";<br>';
                  //dvds[index++]="#Life is Beautiful#dvd1#10.5#10#history#Roberto Benigni#";
                  }
      
              /*** close the database connection ***/
              $dbh = null;
              }
          catch(PDOException $e)
              {
              echo $e->getMessage();
              }
          ?>
          <form action="http://127.0.0.1/DVD_show.php" method="get">
           <p>Please input DVD name: <input type="text" name="name" /></p>
      
           <p><input type="submit" /></p>
          </form>
          '''
      

      请看:

      https://phpdelusions.net/pdo_examples/select

      【讨论】:

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