Display data from a non wordpress database on a page template

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();

Read More

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

Related posts

Leave a Reply

2 comments

  1. 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) {
            ...
        }
    }
    
  2. Where you have this:

    $newdb = new wpdb();
    

    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:

    $newdb = new wpdb(DB_USER, DB_PASSWORD, 'myNewDbName', DB_HOST);