In my site I'd like to pull in data from another table, without having to create an API from the other site. I have seen that you can do something like this:
$wpdbtest_otherdb = new wpdb('myaccount_cityuser', 'mypassword', 'myaccount_cities', 'localhost');
$wpdbtest_otherdb->show_errors();
$mycities = $wpdbtest_otherdb->get_results("SELECT name
FROM city
WHERE city.stadium = 1");
foreach ($mycities as $mycity) {
echo $mycity->name . '<br />';
}
However, I don't like the idea of having everything, including database credentials in one wedge.
What I've tried:
Added credentials to wp-config.php
define('DB_CAREERS_NAME', 'careers');
define('DB_CAREERS_USER', 'root');
define('DB_CAREERS_PASSWORD', '');
define('DB_CAREERS_HOST', 'localhost');
define('DB_CAREERS_CHARSET', 'utf8mb4');
define('DB_CAREERS_COLLATE', '');
Added a function to functions.php
function get_job_listings()
{
// Create new wpdb instance
$connection = new wpdb(DB_CAREERS_USER, DB_CAREERS_PASSWORD, DB_CAREERS_NAME, DB_CAREERS_HOST);
// Assign a table prefix
$connection->set_prefix('');
// Status of jobs to show
$status = "Open";
// Perform query
$query = $connection->prepare(
"SELECT j.*
FROM $connection->job_posts j
WHERE j.status = '%s'
ORDER BY j.created_at DESC",
$status
);
$jobs = $connection->get_results($query);
return $jobs;
}
But I would like to use my secondary database connection like a standard WordPress query, so that all of the query builder functions are available.
WP_Query
,get_posts
etc. are going to be useless unless you're querying awp_posts
table. That's all they're built to do. You might not be building a REST API to access the database externally, but you're still going to need to write a PHP API for doing anything with it.