简体   繁体   中英

Connect to MySQL on Amazon AWS RDS

I typically connect using the following:

$db_host = "localhost";
$db_username = "bill"; 
$db_pass = "mypassword";
$db_name = "theDB";

mysql_connect("$db_host","$db_username","$db_pass", TRUE) or die(mysql_error());
mysql_select_db("$db_name") or die("no database by that name");

I tried changing the host to the RDS endpoint below with no luck:

$db_host = "mysql7.1234567890123.us-west-2.rds.amazonaws.com";

-The security group has inbound rules that allow my IP.

-I've tried adding "10.0.0.0/8" to the security group from Connecting From PHP Server to MySQL Server on Amazon AWS

Other info: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_PHP_legacy.rds.html

There are couple of things and use PDO or mysqli to connect. If you've made sure that you can connect to RDS by setting the right security group, then you've got the main issues squared away.

Connect to Amazon RDS with this in PHP:

$dbhost = $_SERVER['RDS_HOSTNAME'];
$dbport = $_SERVER['RDS_PORT'];
$dbname = $_SERVER['RDS_DB_NAME'];

$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname}";
$username = $_SERVER['RDS_USERNAME'];
$password = $_SERVER['RDS_PASSWORD'];

$dbh = new PDO($dsn, $username, $password);

$link = mysqli_connect($_SERVER['RDS_HOSTNAME'],   $_SERVER['RDS_USERNAME'], $_SERVER['RDS_PASSWORD'], $_SERVER['RDS_DB_NAME'], $_SERVER['RDS_PORT']);

Example 1. Example using PDO to connect to an RDS database

$dsn = 'mysql:host=mydbinstance.abcdefghijkl.us-east-1.rds.amazonaws.com;port=3306;dbname=mydb';
$username = 'sa';
$password = 'mypassword';

$dbh = new PDO($dsn, $username, $password);

Example 2. Example using mysqli_connect() to connect to an RDS database

$link = mysqli_connect('mydbinstance.abcdefghijkl.us-east-1.rds.amazonaws.com', 'sa', 'mypassword', 'mydb', 3306);

if nothing works, launch a mysql client like navicat or mysql workbench (free) and punch in all the necessary fields and try to connect and see if it loads the db.

This ended up working for me. Thanks for you help!

$db_host =      'instance2.123456789.us-west-2.rds.amazonaws.com:3306';     //RDS Endpoint...
$db_username =  'myusername';
$db_pass =      'mypassword';
$db_name =      'myDB'; 


mysql_connect("$db_host","$db_username","$db_pass", TRUE) or die(mysql_error());
mysql_select_db("$db_name") or die("no database by that name");

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