0
votes

i'm coding a project and have some troubles when the system inform error: Invalid argument supplied for foreach() in: foreach($dbh->query($q1) as $row)

and can't get data from the database. How can i fix it, im a newbie, so if i don't understand, please teach me! thanks! thank for your helps but i still can't fix it

<?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
You're using PDO, for the love of sanity, use prepared statements/bind variables - Mark Baker
You don't check that your query succeeds, you just assert it does. It seems not... - Arcesilas

3 Answers

0
votes

Check that your query succeeded before iterating on the result:

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

By the way, I don't understand what you are trying to do with this pointless loop.

0
votes

You could do this

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

Try to make your code more readable

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

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