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() …”
As Ben suggested, you need to pass the connection details when creating the wpdb class:
You should also test that the query actually returned something before using the result in a foreach loop:
Where you have this:
You need to give the new database connection info so it can connect. Assuming you have the same user,password, and host for your new database, you could use a few of the available constants, but you will at least need to define the db name specifically: