Jarla Jarla - 7 days ago 7
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);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

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


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

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'];  
}