Jarla Jarla - 1 year ago 92
MySQL Question

Why do I have an "Invalid argument supplied for foreach" in mysql connection?

Here is my database connection

try {
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";port=8889;dbname=".DBNAME, DBUSER, DBPASS);

} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';

I want select some values from my table:

$pdo = $db->prepare('SELECT * FROM animals ORDER BY id ASC;');
foreach ($pdo->execute($db) as $row) {
echo $row['name'];

But I get two warning messages:

Warning: PDOStatement::execute() expects parameter 1 to be array, object given in...

And the second warning:

Warning: Invalid argument supplied for foreach() in...

Edit, for JonStirling:

$pdo = $db->prepare('SELECT * FROM animals ORDER BY id ASC;');
while ($row = $pdo->fetch()) {
echo $row['name'];

With this solution I do not get any warnings, but also still no results.

Answer Source

One possible solution could be...

$pdo = $db->query('SELECT * FROM animals ORDER BY id ASC;');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
    echo "\n" . $row['name'];  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download