WordPress: Using wpdb to work with an external database

Saul Goodman October 28, 2019 Loading...

This article shows you how to use the wpdb class in WordPress in order to retrieve data from an external database.

// replace username, password, my_database, localhost with your own infomation.
$my_con = new wpdb('username', 'password', 'my_database', 'localhost');

// Executes a SQL query and returns the entire SQL result.
$my_results = $my_con->get_results("SELECT column1, column2, column3, column4 FROM my_table ORDER BY column1 DESC LIMIT 0, 5");

// Display the results
// Replace column1, column2... with your own column names such as id, name, email, title, price...
    foreach($my_results AS $my_result):
            <p>Column1: <?php echo $my_result->column1; ?></p>
            <p>Column2: <?php echo $my_result->column2; ?></p>
            <p>Column3: <?php echo $my_result->column3; ?></p>
            <p>Column4: <?php echo $my_result->column4; ?></p>

// Kill the cached results

From now on, you are pretty good to go.

Welcome to KINDACODE. Have a nice day and code well!