Skip to content
Advertisement

Invalid argument supplied for foreach; PDO

I have seen this and this, but neither of these help my situation, this is why I am knowledgeably opening a question that has been asked before.


My code is:

<?
    $getGame = $database->prepare('SELECT * FROM mainSite_games WHERE id=:gameID');
?>
    <div class='container_12'>
        <div id='contentcont'>
            <div id='content'>
            <?
            if (isset($_GET['gameID'])) {
                $getGame->bindValue(':gameID',$GET['gameID'],PDO::PARAM_INT);
                $getGame->execute();
                $rows = $getGame->fetch(PDO::FETCH_ASSOC);

                foreach ($rows as $game) {

                    $gameName = str_replace(' ','_',strtolower(stripslashes($game['gameName'])));
            ?>
                    <section class='<? echo $gameName; ?>'>


                        <h1><? echo stripslashes($game['gameName']); ?></h1>

                        <p><? echo stripslashes($game['gameDesc']); ?></p>


                        <article class='grid_5 alpha' style='float:left;'>

                            <h3><a href='viewQuests.php?gameID=<? echo $game['id'] ?>'>View <? echo stripslashes($game['gameName']); ?> Quests</a></h3>
                            <p>Offers the ability to see the available quests in <? echo stripslashes($game['gameName']); ?> along with information about them and a simple guide to go along with each.</p>

                        </article>


                        <article class='grid_5 omega' style='float:right;'>

                            <h3><a href='viewDB.php?gameID=<? echo $game['id'] ?>'>View <? echo stripslashes($game['gameName']); ?> Database</a></h3>
                            <p>Offers information about <? echo stripslashes($game['gameName']); ?> items, places, and characters. We try to be extensive with our information.</p>

                        </article>


                    </section>

            <?
                }
            } else {
                echo '<h3>Game ID is not set!</h3>;'
                exit();
            }

            ?>
            </div>
        </div>
    </div>
</body>
</html>
<?
    $database = null;
    unset($database);
?>

The database is initialized and connected to in an include provided by my globhead file:

$function = new srFunc();
try {
    $database = new PDO('mysql:host=localhost;dbname=expunged;charset=utf8','expunged','expunged',array(
        //database attributes
        PDO::ATTR_EMULATE_PREPARES=>false, //use real prepared statements
        PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION, //set errors to kill application
        PDO::ATTR_PERSISTENT=>true //keep the connection open indefinitely
        ));
} catch (PDOException $e) {
    $function->logPDO($e->getMessage());
    exit();
}

logPDO is provided by my functions class:

public function logPDO($err) {
    try {
        $filename = 'logPDO';
        $filehandle = fopen($filename, 'a');
        fwrite($filehandle,'[ '.date('Y-m-d Ga e').' ]  '.$err."nn");
        fclose($filehandle);
    } catch (exception $e) {
        return $e;
    }
}

OK..so now we know how my code works — in the uppermost code box at my foreach, it reports in my error log:

Invalid argument supplied for foreach

Now, changing the line just above ($rows = $getGame->fetch(PDO::FETCH_ASSOC)) to $rows = $getGame->fetchAll(PDO::FETCH_ASSOC) (adding All), nothing is reported. It just becomes a blank page with my styling and structure intact.

I’m not sure what’s going on, and I am very new to PDO, so I’m not sure how to troubleshoot this.

I have tried wrapping this in a try,catch block but nothing was reported (nor logged to file using my log function), so I’m at a loss. Does anyone with more experience with PDO see anything that’s wrong with my code?

Advertisement

Answer

I’m not sure what’s going on, and I am very new to PDO, so I’m not sure how to troubleshoot this.

What’s going on is, that you’ve got an empty database result. If you foreach over an empty result, there are no (zero) iterations. Hence you see no output and hence you see no error. It’s a perfectly fine programming of doing nothing.

How to troubleshoot? I think it’s best to understand the difference between an empty database result and a failed database query. E.g. as long as you have a query that selects rows, there is a rowCount() method with the result object.


Additional remarks:

  • You are using PHP short-tags <?, please see “Are PHP short tags acceptable to use?” and understand the potential problems this carries. We kindly asks users when posting PHP source-code on this website here to not use them to address the question to the general audience (as this is the intention of this website).
  • The output code you have should not contain the database interaction. You can achieve this by only passing the $rows variable in there and move the if-clause around it.
  • Assigning NULL to the $database variable only to unset($database); it is not necessary in PHP.
  • You do not need to unset($database); at all. PHP will clean this up for you when you end the script. If you want to close the database connection in PDP and you’re using mysql, please see “Do SQL connections opened with PDO in PHP have to be closed” and if you really need to close the connection, you can learn how this can be done in this answer to it.
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement