I set up a MySQL RDS instance in AWS. After instantiating the instance I tried to connect it from my EC2's command line and it works with no issue. However, when I try connecting through my PHP code I get erros. Below is the sample code that I tried to test my connectivity.
<?php
try{
$dbh = new pdo( 'aws-test-db.hibizibi.us-west-2.rds.amazonaws.com;dbname=test',
'root',
'password',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
die(json_encode(array('outcome' => true)));
}
catch(PDOException $ex){
die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}
I get {"outcome":false,"message":"Unable to connect"}. My original code is using idiorm (which uses PDO). The portion that connects with database looks like below:
# configure ORM
ORM::configure('mysql:host='.DB_SERVER.';dbname='.DB_NAME);
ORM::configure('username', DB_SERVER_USERNAME);
ORM::configure('password', DB_SERVER_PASSWORD);
From the above I get the below error trace:
SQLSTATE[HY000] [2005] Unknown MySQL server host 'aws-test-db.hibizibi.us-west-2.rds.amazonaws.com:3306' (11)
#0 /var/www/html/main/admin/applications/vendors/idiorm/idiorm.php(255): PDO->__construct('mysql:host=aws-...', 'root', 'password', NULL)
#1 /var/www/html/main/admin/applications/vendors/idiorm/idiorm.php(237): ORM::_setup_db('default')
UPDATE
I updated my test code to try connecting using mysql extension and it worked with mysql but not PDO
<?php
$servername = "aws-test-db.hizibizi.us-west-2.rds.amazonaws.com";
$username = "root";
$password = "password";
$dbname='test';
try{
$dbh = new pdo(
'mysql:'.$servername.';dbname='.$dbname.';',
$username,
$password,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
die(json_encode(array('outcome' => true)));
} catch(PDOException $ex) {
echo json_encode(array('outcome' => false, 'message' => $ex->getMessage()))."\n";
}
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully\n";
Now, I am getting {"outcome":false,"message":"SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '\/var\/lib\/mysql\/mysql.sock' (2)"} while trying t connect through PDO. My attempt through mysql is successful. Seems like the problem is specifically with PDO. Is there anything I can check ?
This is a very old question, but I had the exact same issue and wanted to document it here for anyone who finds this later.
The Problem
You can connect to your database (Amazon RDS) manually from the command line.
You can connect to your database via mysqli in PHP.
You can not connect to your database via PDO in PHP.
The Solution
For me, after trying almost everything, I randomly decided to try and create a new database user. This worked and I was now able to connect via PDO.
This prompted me to investigate the issue a little further and I was able to narrow the issue down to a backslash \ character in my MySQL password.
There seems to be some kind of conflict between ENV Vars (with \), PHP and PDO.
Related
I am trying to connect to (remote) AWS MYSQL database using php and ssl.
I created a database user and could connect with it from php and also on console.
Then I modified the user to use SSL with "require ssl" in the database.
I can stil connect on the console by:
mysql -h host -u username -p --ssl
But in php I get an ERROR 2002.
$con=mysqli_init();
mysqli_ssl_set($con,NULL,NULL,"cacert.pem",NULL,NULL);
$link = mysqli_real_connect($con, "host", "username", "password");
As far as I know the ssl_set parameters doesn't matter with AWS databases.
How to connect to Amazon RDS via SSL?
I think it has to do with the mysqli_ssl_set method, without it a connection is made and access is denied by database and this is the correct behaviour. It might be some configuration error on client side, but I have no idea what I shoud check.
The error is fired by mysqli_real_connect, as mysqli_ssl_set always returns true, just after it tries to connect will it receive an error.
I noticed it did not work for me until I specified the port. The following worked:
$db = mysqli_init();
$db->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, true);
$db->ssl_set(NULL, NULL, 'rds-combined-ca-bundle.pem', NULL, NULL);
$db->connect($host, $user, $pass, $db, 3306);
$servername = "only-ssl-db.ct5b4uz1gops.eu-central-1.rds.amazonaws.com";
$username = "username";
$password = "password";
$dbname = "dbname";
$con = mysqli_init();
if (!$con){
die("mysqli_init failed");
}
mysqli_ssl_set($con,NULL,NULL,'rds-combined-ca-bundle.pem',NULL,'DHE-RSA-AES256-SHA');
if (!mysqli_real_connect($con,$servername, $username, $password, $dbname))
{
die("Connect Error: " . mysqli_connect_error());
}
// Some queries...
echo "Database connected";
printf("Client version: %d\n", mysqli_get_client_version());
mysqli_close($con);
I am creating a pdo data connection. The connections works fine on localhost.
But when I connect to my remote db, and use exactly the same credentials which I have used before, I get a empty page, no error messages, just a empty page.
The same credentials that are working on a previous project were done with mysqli, this one is done with pdo.
I have tried two types of pdo connection code, none of them are working.
First one:
$databaseHost = 'x.xxx.xxx.xx';
$databaseName = 'xxxxxxxxx';
$databaseUsername = 'xxxxxxx';
$databasePassword = 'xxxxxx';
$charset = 'utf8';
try {
$dsn = "mysql:host=$databaseHost;dbname=$databaseName;charset=$charset";
} catch(PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $databaseUsername, $databasePassword, $opt);
Second one:
$databaseHost = 'x.xxx.xxx.xx';
$databaseName = 'xxxxxxxxx';
$databaseUsername = 'xxxxxxx';
$databasePassword = 'xxxxxx';
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO("mysql:host={$databaseHost};dbname={$databaseName}", $databaseUsername, $databasePassword, $opt);
} catch(PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Even though both connections work in localhost, I tried to just load this connection page locally in the browser, the fist option gave me this error:
Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] Operation
timed out in /Applications/MAMP/htdocs/ijdb_pdo/config.php:24 Stack
trace: #0 /Applications/MAMP/htdocs/ijdb_pdo/config.php(24):
PDO->__construct('mysql:host=83.1...', 'u1164707_sohail', 'sohail123',
Array) #1 {main} thrown in
/Applications/MAMP/htdocs/ijdb_pdo/config.php on line 24
and the second option gave me the following error:
againtestConnection failed: SQLSTATE[HY000] [2002] Operation timed out
What am i messing up in my code?
I tried then to connect through the terminal with:
MacBook-Pro-3:/ sohail$ /Applications/MAMP/Library/bin/mysql -h "xx.xxx.xxx.xx" -u "xxxxxx" "-pxxxxxxx" "xxxxxxx";
and got the following error:
Warning: Using a password on the command line interface can be
insecure. ERROR 2003 (HY000): Can't connect to MySQL server on
'xx.xxx.xxx.xx' (60) MacBook-Pro-3:/ sohail$
I don't think I have terminal access on my remote machine, so I can't do SHOW GLOBAL VARIABLES LIKE 'PORT'; cmd
-thanks
For your second error, with reference to these two answers.
PDOException SQLSTATE[HY000] [2002] Connection timed out on my local computer
'PDOExcpetion' with message 'SQLSTATE[HY000] [2002] No route to host
Either you need to enable the access to remote database or you have network IP issue which changes time to time. Please verify both things. I hope this will help you.
In my case,
somehow the database connection credential was changed.
I had this issue with a Laravel App in Vagrant. I cleared the config cache and then it worked fine.
php artisan config:cache
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I do not believe the question to be a duplicate as I believe the issue is related to Shared Hosting environments getting outbound to other cloud mysql servers.
Error message
PDO Exception: SQLSTATE[HY000] [2002] Connection timed out.
I am simply just trying to connect to my instance of AWS RDS and run a query on one of my tables.
SOLUTION: GODADDY BLOCKS ALL PORTS EXCEPT 21 AND 22 (FTP) ON A STANDARD ACCOUNT. THIS IS WHAT I WAS TOLD BY GODADDY TECHNICAL SUPPORT. HENCE, IT WILL BLOCK PORT 1234 AND EVEN 3306 FOR A DATABASE CONNECTION.
UPDATE:
#Drew has validated that this php code works for the connection:
try {
$db = new PDO('mysql:host=uwmparkingbackend.cb7gmuw49vhs.us-east-1.rds.amazonaws.com;port=1234;dbname=uwm_parking;charset=utf8', 'fbgrecojr', 'test1234');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
echo "Connected and Happy<br>";
$sql="select id,thing from thingsCoveted where id in (1,3)";
foreach ($db->query($sql) as $row) {
print $row['id'] . "\t";
print $row['thing'] . "<br>";
}
} catch (PDOException $e) {
echo 'PDO Exception: ' . $e->getMessage();
exit();
}
I am getting this error however on my end:
PDO Exception: SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'uwmparkingbackend.cb7gmuw49vhs.us-east-1.rds.amazonaws.com' (110)
Hence, there is either a config issue on the Godaddy side (where the .php is hosted) or the AWS RDS side (where the database is hosted);
Things I have tried:
1) checked to make sure all PDO options are selected in GoDaddy's php settings
2) added an inbound rule for my AWS RDS security group to allow all connections using my port (1234).
The problem is you've just copied and pasted your connection info into the example given by Amazon inside the $_SERVER array.
// Example
$link = mysqli_connect($_SERVER['RDS_HOSTNAME'], $_SERVER['RDS_USERNAME'], $_SERVER['RDS_PASSWORD'], $_SERVER['RDS_DB_NAME'], $_SERVER['RDS_PORT']);
// What yours should be
mysqli_connect(
'***********.******.us-east-1.rds.amazonaws.com',
'*******',
'********',
'dbname',
'1234'
);
You also need to use mysqli functions since that's how you're connecting, e.g. http://php.net/manual/en/mysqli.query.php
EDIT:
Now you're using PDO you will need to take a different approach to getting your data.
$dbhost = '***********.******.us-east-1.rds.amazonaws.com';
$dbport = 3306;
$dbname = '*****';
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname}";
$username = '*****';
$password = '*****';
try {
$dbh = new PDO($dsn, $username, $password);
$query = $dbh->query("SELECT num_spaces FROM uwm_parking.lots");
while($row = $query->fetch(PDO::FETCH_OBJ)) {
var_dump( $row );
}
} catch(PDOException $e ){
echo "Error: ".$e;
}
I am trying to connect to a mssql server on my mac through pdo_dblib. I have the freetds.conf updated to the host I want to connect. My phpinfo tells me that I have all the driver hooked up and good to go. Below is the code that I wrote to test if I can connect to the server.
<?php
$servername = "IP";
$port = "port";
$username = "username";
$password = "password";
$myDB = "database";
try {
$conn = new PDO("dblib:dbname=$myDB;host=$servername:$port", "$username", "$password");
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
However I get an error:
Connection failed: SQLSTATE[] (null) (severity 0)
I tried using SQL Developer to connect to the mssql server and it worked. I have been trying to solve this problem for a whole day. What might be the problem? Thanks!
Remove the quotes from the variables in the connection string -
$conn = new PDO("dblib:dbname=$myDB;host=$servername:$port", $username, $password);
I found out the answer!
You have to uncomment TDS version protocol in /usr/local/Cellar/freetds/0.91/etc/freetds.conf.
Found the solution in Why won't my server connect to a remote MSSQL server using PHP mssql_connect?
but why do I have to do this...no idea...wish some one could give some explanation.
I am working on a website that runs by MYSQL and Linux Php 5.3 - and i need to work with this as well as a remote MSSQL database.
I read that PDO this is the way to connect to MSSQL.
It though seems there are both a PDO and a more familiar mssql_connect solution.
I have little to no experience with either PDO or mssql_connect.
On the PHP documentation i find:
Mssql_connect - The familiar expression:
<?php
// Create a link to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
// Select the database 'php'
mssql_select_db('php', $link);
?>
PDO - Which i haven't tried before - which needs a driver !(?) :
<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
So what to choose and why ?
Although I have not tried it yet. So I can't say for sure if it works or not.
PHP Manual says use pdo::dblib http://php.net/manual/en/ref.pdo-dblib.php
Microsoft does have it's own set of drivers but you have to be on a windows machine to use them. http://www.microsoft.com/en-us/download/details.aspx?id=20098
MSSQL connection with PDO:
$db_handle = new PDO("sqlsrv:server=$server; Database=$database", $user, $pass);
MySQL connection with PDO:
$db_handle = new PDO("mysql:host=$server;dbname=$database", $user, $pass);
I don't see what your confusion is?