I am using a sql query to access information to display on a wordpress page by adding the below code to a page template. I know the query works as I’ve tested it in phpmyadmin.

 $rows = $newdb->get_results("SELECT TrainerName FROM trainers");   
 echo "<ul>";
 foreach ($rows as $obj) :
 echo "<li>".$obj->Name."</li>";
 endforeach;
 echo "</ul>";

and I added this is my functions.php file
$newdb = new wpdb();
$newdb->show_errors();

I can’t get it to work though, I get an error “Warning: Invalid argument supplied for foreach() …”

2 Answers
2

As Ben suggested, you need to pass the connection details when creating the wpdb class:

$newdb = new wpdb( 'user', 'password', 'database', 'hostname' );

You should also test that the query actually returned something before using the result in a foreach loop:

if ($rows) {
    foreach ($rows as $obj) {
        ...
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *