1

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."\n\n");
        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?

Community
  • 1
  • 1
  • 1
    This isn't your immediate problem, but lines like this do nothing for you: ` echo stripslashes($game['gameName']); ?>` Use `htmlspecialchars()` instead. Also, try dropping your attributes for `ATTR_EMULATE_PREPARES` and `ATTR_PERSISTENT`. – Brad May 05 '13 at 08:05
  • 1
    Does `$getGame->execute();` return false? I suspect it may do that when you bind a string as an int; `$getGame->bindValue(':gameID',$GET['gameID'],PDO::PARAM_INT);` – Joachim Isaksson May 05 '13 at 08:13
  • @JoachimIsaksson gameID is an int though, where am I binding a string as an int? It seems that I'm binding an int as an int, did I make an error? –  May 05 '13 at 08:27
  • 1
    @JacobAndersen `$_GET['gameID']` returns the string `'42'`, not the int `42`. You may need to convert it before passing it to `bindValue`, as in `$getGame->bindValue(':gameID',intval($GET['gameID']),PDO::PARAM_INT);` I'm hardly a PDO expert though :) – Joachim Isaksson May 05 '13 at 08:31
  • @JoachimIsaksson Thanks, unfortunately that did nothing, but thanks for your effort! –  May 05 '13 at 08:35

3 Answers3

0

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.
Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
  • Sorry if the humor bothered you. Here is the story behind the joke: In PHP using `unset($var)` or `$var = NULL` is pretty much the same, so doing the one before the other is just superfluous. – hakre May 05 '13 at 09:04
-1

I had $GET and not $_GET in my bind value statement. Make sure to check your underscores, people!

Okay, good night. I'm up too late.

-2

Please check your

$dns = "mysql:host=localhost;dbname=xxx";
$db = new PDO($dns , 'user' , 'password');

there should not be any white space in $dbs. (eg. $dns = "mysql: host=localhost ;dbname=xxx"; )

Jouby
  • 2,196
  • 2
  • 21
  • 33
  • i had same problem. for PDO you need to create " database source name or DSN". This is simply a string that identifies the database you want to connect to. the dns i created was having white spaces like -> ($dns = "mysql: host=localhost ;dbname=xxx";). then i removed white spaces like->($dns = "mysql:host=localhost;dbname=xxx";). and every thing start working – Nischint Pal Feb 14 '20 at 05:53