Connect to MySql PDO Database

I am learning PDO and I am very confused, I have this code below and everything looks correct, but I get this error code and I don’t know what I need 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

+6
source share
1 answer

Try increasing the 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 also use pdo.errorcode and pdostatement.errorcode (or something like that) to get more information, but I think the throw exception is the best way to handle bad connections, not allowed hosts, etc. .d.

+16
source

All Articles