6

I am learning PDO and i am getting very confused, I have this piece of code below and all looks right to me however I'm getting this error code and I don't know what I have to do to fix it, please help me:

<?php
$hostname='localhost';
$username='root';
$password='';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=stickercollections",$username,$password);
    echo 'Connected to Database<br/>';
    
    $sql = "SELECT * FROM stickercollections";
foreach ($dbh->query($sql) as $row)
    {
    echo $row["collection_brand"] ." - ". $row["collection_year"] ."<br/>";
    }
    
    
    $dbh = null;
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
?> 

Error Code

Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/GOTSWAPMAIN/index.php on line 11
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Marc Guerin
  • 7,192
  • 3
  • 16
  • 12
  • 4
    `var_dump($dbh->query($sql))` --- always check what's inside variables and what expressions return instead of guessing – zerkms Oct 31 '12 at 22:07
  • 1
    As zerkms hinted at, it looks like the query is failing and is thus returning false instead of an iterable PDOStatement. It looks like you're trying to use PDO with exceptions. If the connection were configured to use exceptions, you wouldn't get this invalid argument error since an exception would be thrown (and thus the foreach would never be executed). You have to tell the connection to throw exceptions though, either view the fourth parameter of PDO::__construct or via `$dbh->setAttribute`. – Corbin Oct 31 '12 at 22:13

1 Answers1

23

Try to increase error mode:

<?php
$hostname='localhost';
$username='root';
$password='';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=stickercollections",$username,$password);

    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
    echo 'Connected to Database<br/>';

    $sql = "SELECT * FROM stickercollections";
foreach ($dbh->query($sql) as $row)
    {
    echo $row["collection_brand"] ." - ". $row["collection_year"] ."<br/>";
    }


    $dbh = null;
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
?> 

EDIT: pdo.error-handling says, you can alternatively use pdo.errorcode and pdostatement.errorcode (or like) to get more info, but I think throw exception is better way to handle bad connections, not resolved hosts etc.

Anton Bessonov
  • 9,208
  • 3
  • 35
  • 38
  • Thank you, thats done it, I knew it was with the setAttribute but was confused as to which one and where, Thanks for yor quality in the reply. – Marc Guerin Oct 31 '12 at 22:28