1

I'm trying to connect to an external database on AWS RDS to display data from the external database in WordPress, using a plugin I'm writing.

My only issue is connecting to the external database and pulling information from it.

Additionally, I need to be able to update info in the external database as well.

I'm trying to use $awsdb = new wpdb( 'username', 'password', 'database', 'localhost' ); but it doesn't seem to be working.

RDS has slightly different access details to a regular MySQL db, and I'm unfamiliar with RDS.

The details I have to work with are:

adapter: mysql
encoding: utf8
database: database_name
username: username
password: password
host: thedatabase.0000000000.location-1.rds.amazonaws.com
port: 0000

I have been placing the info in how I thought would be correct:

$awsdb = new wpdb( 'username', 'password', 'database_name', 'thedatabase.0000000000.location-1.rds.amazonaws.com' );

but that doesn't seem to work.

I also tried it with the port appended:

$awsdb = new wpdb( 'username', 'password', 'database_name', 'thedatabase.0000000000.location-1.rds.amazonaws.com:0000' );

I'm kinda lost on this trivial piece to the puzzle.

Here is the function I'm testing by trying to display a list of the stored usernames in the external table:

function test_connect_to_db() {
    $awsdb = new wpdb( 'username', 'password', 'database_name', 'thedatabase.0000000000.location-1.rds.amazonaws.com' );
    $rows = $awsdb->get_results( "SELECT * FROM table"  );
    echo '<div style="clear:both;text-align:center;"><h1>DB DETAILS</h1></div>';
    echo '<ul>';
    foreach ($rows as $obj) {
        echo '<li>'.$obj->user_id.'</li>';
    }
    echo '</ul>';

}
add_action( 'init', 'test_connect_to_db' );

Note: I have omitted actual connection credentials and used placeholder text.

1

I was able to get a working connection using the following code:

function test_connect_to_db() {

    $servername = 'thedatabase.0000000000.location-1.rds.amazonaws.com';
    $username = 'username';
    $password = 'password';
    $dbname = 'database';

    // Create connection
    $conn = new mysqli( $servername, $username, $password, $dbname );

    // Check connection
    if ( $conn->connect_error ) {
        die( 'Connection failed: ' . $conn->connect_error );
    } 

    $sql = 'SELECT id, firstname, lastname FROM table';
    $result = $conn->query( $sql );

    if ( $result->num_rows > 0 ) {
    // output data of each row
        while ( $row = $result->fetch_assoc() ) {
            echo '<br> id: '. $row['id']. ' - Name: '. $row['firstname']. ' ' . $row['lastname'] . '<br>';
        }
    } else {
        echo '0 results';
    }

    $conn->close();

}
add_action( 'init', 'test_connect_to_db' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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