0

So I have multiple databases associated with the database where my wordpress website is hosted. I was wondering if I can access all of said databases with $wpdb or will I need to initiate a connection using mySQL credentials for said database. Here is my code, it is returning a 500 error so I know the issue is on the server side. On the server I have various databases with the same prefix followed by _"suffix". Below I am trying to access the database pre_schools which is a separate database from where I find all the essential wp stuff ie. wp posts, users, etc. I tried initiating a new WP connection as well and no dice either. If anyone has any idea the direction to push me in it would be much appreciated.

 <?php
/*
Plugin Name:  College ID API
* Requires PHP: 7.2
*/

function collegeid(WP_REST_Request $request)
{

    global $wpdb;
    $schools=$wpdb::select("pre_schools");
    $data = $schools->get_results("SELECT Colleges ' . $wpdb->prefix . '");
    return $data;

};



add_action( 'rest_api_init', function () {
    register_rest_route( 'wp/v1', '/schools', array(
        'methods' => 'GET',
        'callback' => ['collegeid'],
        'permission_callback'=>'__return_true' 
    ) );
} );





?>
1
  • 1. Are you sure you need to directly access the database? In most cases you can accomplish what you need with WP functions. 2. If you do need to access the DB, you'll need to read up on the wpdb class and its methods. For example, select() is not a static method, and your get_results() will be something like SELECT Colleges wp_, which... won't work.
    – Pat J
    May 30, 2023 at 18:44

1 Answer 1

1

You can access another database using the wpdb class and its associated methods. You will need to instantiate a new connection to the other database using the appropriate credentials. Here is the basic code to set up the new connection and query the database:

$mydb = new wpdb('username','password','database','localhost');
$rows = $mydb->get_results("<your SQL query here>");

Replace the parameters to the wpdb() method as required and construct the necessary query for get_results().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.