No such file or directory connecting to RDS through EC2 with php

1.8k Views Asked by At

I've set up an RDS and an EC2 on amazon web services. The RDS is in one security group, and the EC2 in another. The EC2 security group accepts http, https and ssh traffic (though I have tried setting it to all traffic) from any location, while the RDS security group accepts all inbound traffic from itself, and the EC2 security group.

I have some php files on the EC2, with

$server = $_SERVER['DB_SERVER'];
$username = $_SERVER['DB_USERNAME'];
$password = $_SERVER['DB_PASSWORD'];
$database = $_SERVER['DB_DATABASE'];

$connection = new mysqli($server, $username, $password, $database);
echo $connection->connect_error;

where DB_SERVER etc are listed in dbinfo.inc in /var/www/inc/dbinfo.inc, as per this tutorial: http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Tutorials.WebServerDB.CreateWebServer.html

This gives the response "No such file or directory", which I am told is because the mysql.sock file is not being found.

In /etc/my.cnf I have:

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
*bunch of comments*

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

but no mysql.sock exists in /var/lib/mysql (or /var/lib/mysql/mysql)

Running

find . mysql.sock 

and

find . mysqld.sock 

both give "No such file or directory"

Thanks for your help

1

There are 1 best solutions below

0
sukant kalpande On

I had faced same problem while I was trying to deploy php application on aws ec2 and hosting database on rds

First of all, do not follow the amazon documentation for connecting rds database. reason $_server['anything'] returns empty value. So
$server = $_SERVER['DB_SERVER']; in here $server holds nothing but a empty value

Use following code instead:

<?php
$dbhost = 'your rds instance endpoint';
$dbport = 'port numberdefault 3306 ';
$dbname = 'name of data base';
$charset = 'utf8' ;
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset=   {$charset}";
$username = 'username ';
$password = 'password';

try {

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

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "your sql query";

$pdo->exec($sql);
echo "successfully connected"; 
}
catch(PDOException $e)
{
t;    
echo "Connection failed: <br>  ". $e->getMessage(); 

}

$conn = null;

?>