简体   繁体   中英

How do I do MySQL queries on an RDS instance from an EC2 instance?

I've been trying to set up a system where my database will be in an AWS RDS instance and my programs in a EC2 instance (seemingly very straightforward)

For some reason following the results here have been pretty unhelpful.

To clarify, what I'm looking for is some sample code to connect to a db and run mysql queries. So far my every attempt ends with my program trying to connect with my localhost mysql on my ec2 instance despite specifying the rds url.

Here's my script,

<?php
$servername = "maindb.gibberish.us-east-1.rds.amazonaws.com";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (mysqli_error($conn)) {
    die("Connection failed: " . mysqli_error($conn));
}else{
        echo "connected successfully";    
}
?>

You can use the code in my answer to this question which also explains what each line of code does. You would type your amazon RDS endpoint in the $servername variable. and also change your query in the $sql variable.

In terms of ensuring that your RDS can be contacted by your EC2 Server. you need to ensure that the security group is correctly set to allow connections from your server. like so:

1. In your EC2 Management Console, select 'Security Groups' from the left side navigation. 图。1

2. Select the security group for your RDS server . nb If you didn't name this something specific when you set it up then the name is likely to look like rds-launch-wizard created xxxxxxx . 图2

Click the edit button. It is likely that the IP address which is in there, is the one which you are working from. (Or the one which you were on when you setup the server). You need to change this to either ANY, or just your EC2 server's public IP address.

EDIT: after looking at your code I think you are testing the connection incorrectly.

<?php
$servername = "maindb.gibberish.us-east-1.rds.amazonaws.com";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {

    die("Connection failed: " . mysqli_error($conn));

}else{
        echo "connected successfully";

}


?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM