为foreach()提供的参数无效

时间:2016-05-13 18:24:19

标签: php sql

我正在编写项目并在系统通知错误时遇到一些麻烦:  为foreach()提供的参数无效:  foreach($ dbh-> query($ q1)as $ row)

并且无法从数据库中获取数据。我怎么能解决它,我是新手,所以如果我不明白,请教我!谢谢! 谢谢你的帮助,但我还是无法解决它

<?php include("top.html"); ?>

<body>

    <div id="main">
        <h1>Results for <?php echo $_GET['firstname'] . " " . $_GET['lastname'] ?></h1> <br/><br/>
        <div id="text">All Films</div><br/>
        <table border="1">
            <tr>
                <td class="index">#</td>
                <td class="title">Title</td>
                <td class="year">Year</td>
            </tr>
            <?php

    $dbh = new PDO('mysql:host=localhost;dbname=imdb_small', 'root', '');


    $q1 = "SELECT id 
            FROM actors 
            WHERE first_name = '".$_GET['firstname']."'  AND last_name = '".$_GET['lastname']."' 
            AND film_count >= all(SELECT film_count 
                                    FROM actors 
                                    WHERE (first_name LIKE'".$_GET['firstname']." %' OR first_name = '".$_GET['firstname']."') 
                                    AND last_name = '".$_GET['lastname']."')";
    $id = null;

    foreach($dbh->query($q1) as $row){
        $id = $row['id']    ;
    }
    if($id == null){
        echo "Actor ".$_GET['firstname']." ".$_GET['lastname']."not found.";  
    }
    `
                $sql2 = "SELECT m.name, m.year 
                 FROM movies m 
                 JOIN roles r ON r.movie_id = m.id 
                 JOIN actors a ON r.actor_id = a.id 
                 WHERE (r.actor_id='".$id."') 
                 ORDER BY m.year DESC, m.name ASC";

            $i = 0;
            foreach($dbh->query($sql2) as $row){
                echo "<tr><td class=\"index\">";
                echo $i+1;
                echo "</td><td class=\"title\">";
                echo $row['name'];
                echo "</td><td class=\"year\">";
                echo $row['year'];
                echo "</td></tr>";
                $i++;
            }
            $dbh = null;
            ?>

        </table>

    </div>
</div>
<?php include("bottom.html"); ?>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

你可以这样做

$st = $dbh->query($q1);
if ( $st ) {
    while ( $row = $st->fetch() ) {}
}
  

尝试使代码更具可读性

答案 1 :(得分:0)

在迭代结果之前检查您的查询是否成功:

if (false !== ($result = $dbh->query($d1))) {
    foreach($result as $row){
        $id = $row['id']    ;
    }
}

顺便说一句,我不明白你在用这个毫无意义的循环做什么。

答案 2 :(得分:-1)

$result = $dbh->query($q1);

foreach($result as $row){$id = $row['id'];}