Parris Varney
Parris Varney

Reputation: 11478

PDO cannot connect to MySQL but CLI can

Made a test script:

<?php
$a = new PDO('mysql:dbname=mydbname;host=mydbhost:3306', 'myusername', 'mypassword');
var_dump($a);

I get the following error:

PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2005] Unknown MySQL server host 'mydbhost:3306' (107)' in /users/pvarney/test_pdo.php:3 Stack trace:
#0 /users/pvarney/test_pdo.php(3): PDO->__construct('mysql:dbname=my...', 'myusername', 'mypassword')
#1 {main}   thrown in /users/pvarney/test_pdo.php on line 3

Then via CLI:

[pvarney@ci-server ~]$ mysql mydbname -h mydbhost -u myusername -p --port=3306
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 828511

... snip mysql welcome text ...

mysql>

I've changed the connection string to mask connection information, but I did copy-paste it into the CLI to make sure I didn't have any typos.

Upvotes: 0

Views: 300

Answers (5)

OSXMonk
OSXMonk

Reputation: 588

This worked for me:

  1. Open file something like /etc/php5/cli/php.ini
  2. Find the entry pdo_mysql.default_socket=/opt/lampp/var/mysql/mysql.sock
  3. Change that to what you want. That's all.

Upvotes: 0

NoobEditor
NoobEditor

Reputation: 15881

 $a = new PDO('mysql:dbname=mydbname;host=mydbhost;port=3306', 'myusername', 'mypassword');
                                                 /*note ^^*/

Upvotes: 2

hjpotter92
hjpotter92

Reputation: 80639

Check the PHP docs for PDO_MYSQL_DSN. The port should be passed as a separate parameter:

mysql:dbname=mydbname;host=mydbhost;port=3306

Upvotes: 3

Ram Sharma
Ram Sharma

Reputation: 8809

change

new PDO('mysql:dbname=mydbname;host=mydbhost:3306', 'myusername', 'mypassword');

to

new PDO('mysql:dbname=mydbname; host=mydbhost; port=3306;', 'myusername', 'mypassword');

Upvotes: 4

ovi
ovi

Reputation: 576

Take a look at this post : Not able to connect to MySQL server using PDO

Try changing the port setting

Upvotes: 2

Related Questions