2

I'm attempting to output the contents of my mysql database but no matter what method I use it errors, here is the code I'm using now;

try 
{
    $dbh = new PDO("mysql:host = $hostname; dbname = kzkcubcy_webDev", $username, $password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database<br />';

    /*** The SQL SELECT statement ***/
    $sql = "SELECT * FROM animals";
    foreach ($dbh->query($sql) as $row)
    {
        print $row['animal_type'] .' - '. $row['animal_name'] . '<br />';
    }

    /*** close the database connection ***/
    $dbh = null;
}
catch(PDOException $e)
{
    echo $e->getMessage();
}
?>

The error Its outputting is " Warning: Invalid argument supplied for foreach() in /home/kzkcubcy/public_html/index.php on line 21 "

and line 21 is; " foreach ($dbh->query($sql) as $row) ". I've tired so many other methods at getting this to work but even copying word for word from tutorials doesn't seem to work.

cHao
  • 84,970
  • 20
  • 145
  • 172
user1725794
  • 247
  • 1
  • 5
  • 14
  • 2
    You don't set the error mode to Exceptions. Try doing that because I think there's probably an error in your query of some kind. – Explosion Pills Dec 18 '12 at 04:41
  • possible duplicate of [Invalid argument supplied for foreach()](http://stackoverflow.com/questions/7490577/invalid-argument-supplied-for-foreach) – Jocelyn Dec 23 '12 at 02:48

1 Answers1

5

change

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

to

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

I don't think you are allowed to have spaces in the DSN field.

kittycat
  • 14,983
  • 9
  • 55
  • 80