Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm getting this error code: Invalid argument supplied for foreach() [duplicate]

Tags:

sql

php

pdo

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
like image 907
Marc Guerin Avatar asked Oct 31 '12 22:10

Marc Guerin


1 Answers

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.

like image 85
Anton Bessonov Avatar answered Nov 10 '22 08:11

Anton Bessonov