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
Related
I'm trying to make a connection to the database while having the database config information saperated from the connection.
This is the code I wrote
db config information:
$config = array(
"database" => array(
"host" => "host",
"username" => "username",
"password" => "password",
"name" => "name",
)
);
define("databse_config", $config["database"]);
$config normaly also contains other information not relevant to the question ,that is why I have defined "database_config".
database connection:
require_once "config.php";
define("DB_HOST", databse_config['host']);
define("DB_USERNAME", databse_config['username']);
define("DB_PASSWORD", databse_config['password']);
define("DB_NAME", databse_config['name']);
function connect()
{
$dbhost = DB_HOST;
$dbuser = DB_USERNAME;
$dbpass = DB_PASSWORD;
$dbname = DB_NAME;
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->exec("set names utf8");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
connect();
The problem I keep running in to is that wile trying to execute the function the page keeps loading and eventualy outputs the following error:
Connection failed: SQLSTATE[HY000] [2002] Connection timed out
I'm fairly new to PDO so I also tried the same while using mysqli, which gave the same result.
Any help would be appreciated.
Connection failed: SQLSTATE[HY000] [2002] Connection timed out
This means php tried to establish a TCP/IP connection to your database server AND FAILED. You provided a DB_HOST hostname that's unreachable by network from the location of your php program.
The hostname value could be missing, or it could be wrong. If you provided it by name (mysql-server.example.com), this error message tells you the DNS name lookup succeeded.
So your php sends out a request to the server for a TCP/IP connection. That request never gets a response. That means there's a firewall somewhere blocking the connection, or that there's no network route from your php program to the network.
This all means the $dbhost value is wrong in your new PDO() operation.
Your code could be simplified a lot like this with no loss of modularity. sprintf() helps. Simpler is better for troubleshooting.
require_once "config.php";
function connect()
{
try {
$connectionString = sprintf ("mysql:host=%s;dbname=%s",
database_config['host'],
database_config['name']);
$conn = new PDO($connectionString,
database_config['username'],
database_config['password']);
$conn->exec("set names utf8");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
connect();
And you can echo $connectionString; to see what's in it, and make sure it isn't something bizarre.
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.
I am trying to create a simple mailing list webpage. Using LAMP. Here is the code I have for connecting to my database:
<?php
function insert()
{
$servername = "127.0.0.1";
$username = "root";
$password = "(my password here)";
$dbname = "(my db name here)";
try
{
// preparing database handle $dbh
$dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo ("Could not connect to server.\n");
echo ("getMessage(): " . $e->getMessage () . "\n");
}
}
?>
The function continues after that but this connection attempt gets cung up on the catch, and throws the "SQLSTATE[HY000] [2002] Connection refused" error. I have tried:
-Changing the $servername to localhost, but this gives me a different error: "SQLSTATE[HY000] [2002] No such file or directory"
-trying to specify all different ports
-checked all my info, database name and password.
-I can log into phpmyadmin and see that my database is fine
-looked at all other questions on this topic, with no help found.
I cant figure out why i am not connecting to my db. It seems like it is finding the host but having authentication problems or something. I am using xampp and the db provided with it. My connect code is as follows
<?php
$servername = 'localhost:1234';
$username = 'protech';
$password = '';
$dbname = 'protech';
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}else{
echo "Connected successfully";
}
mysqli_close($conn);
exit;
?>
if you need any information I am by my computer and will respond quick.
I get these error messages after waiting a while.
Warning: mysqli::__construct(): MySQL server has gone away in C:\xampp\htdocs\protech_connect.php on line 9
Warning: mysqli::__construct(): Error while reading greeting packet. PID=7764 in C:\xampp\htdocs\protech_connect.php on line 9
Warning: mysqli::__construct(): (HY000/2006): MySQL server has gone away in C:\xampp\htdocs\protech_connect.php on line 9
Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\protech_connect.php on line 9
The standard port for mySQL is 3306 - so if you are genuinely using 1234 then append that as a new parameter to the db connection constructor.
$dbhost = 'localhost';
$dbuser = 'protech';
$dbpwd = 'xxx';
$dbname = 'protech';
$dbport = 1234;
$conn = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname, $dbport );
if( $conn->connect_error ) exit( 'Bad foo: '.$conn->connect_error );
else { /* do exciting things */ }
$conn->close();
The mysqli_connect() function doesn't accept a port in the host parameter. You need to add the port number in another parameter like so:
$conn = mysqli_connect($servername, $username, $password, $dbname, $serverport);
Function documentation: mysqli::__construct()
If you get following error or problem then follow above solution.
Error:
Warning: mysqli_connect(): MySQL server has gone away
Warning: mysqli_connect(): Error while reading greeting packet. PID=3528
Warning: mysqli_connect(): (HY000/2006): MySQL server has gone away
Solution 1:
use 127.0.0.1 instead of localhost. Don't use any port number after 127.0.0.1.
Solution 2:
Check your host file located at
C:\Windows\System32\drivers\etc
and remove any localhost or 127.0.0.1 entry in file and save. You can use any HostEditor program to edit this file.
I have run into a very confusing issue with connecting to a database via PHP PDO using exec().
I have thrown together the following snippet to illustrate my point.
$host = "localhost";
$db_name = "some_db";
$user_name = "some_user";
$pass_word = "some_password";
try {
// assign PDO object to db variable
$dbh = new PDO("mysql:host=$host;dbname=$db_name;charset=utf8", $user_name, $pass_word, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
echo "yahoo connected";
}
catch (PDOException $e) {
//Output error - would normally log this to error file rather than output to user.
echo "Connection Error: " . $e->getMessage();
}
When I run this code via the browser it connects fine but when I run it at the command line it gives the following error:
Connection Error: SQLSTATE[28000] [1045] Access denied for user 'some_user'#'localhost' (using password: NO)
Needless to say that this is confusing as the password is indeed set as you can see in the code above and the connection works and prints yahoo to the screen in the browser. Any ideas are appreciated.
Your snippet is wrong. It ought to be without useless try-catch block:
$host = "localhost";
$db_name = "some_db";
$user_name = "some_user";
$pass_word = "some_password";
$dsn = "mysql:host=$host;dbname=$db_name;charset=utf8"
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
// other options
);
$dbh = new PDO($dsn, $user_name, $pass_word, $opt);
echo "yahoo connected";
this way you will get a complete error message,including stack trace which will show you the actual file you runs - in which there is empty password used.
it is also important to have error_reporting(E_ALL); to tell you possible issues with variables scope