Connecting through MySQL socket with Zend Framework
-
22-07-2019 - |
Question
I have recently started using Zend Framework. I started developing on my local XAMPP server which went fine but when I uploaded to my 1and1 account, I keep getting the following error:
Message: SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
I have tried changing the resources.db.params.unix_socket line in my application.ini file to the different ones mentioned in phpinfo but with no success. I found here that someone answered
Is the MySQL server on the same host as the web application? If not, you can't use a socket connection, and will need to connect via TCP.
I think that is the case with my web host. How can I change ZF to connect via TCP instead? I am currently using PDO_MYSQL.
Solution 2
I had left the line:
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'development'));
in my index.php as is but had changed public/.htaccess to
SetEnv APPLICATION_ENV production
It looks like the .htaccess was not being read. I changed the else statement in index.php to 'production' to use the production database settings and it worked. Quite frustrating. I wonder why the environment variable was not being read. Thanks for your help.
OTHER TIPS
How you connect to MySQL depends on the parameters you pass to mysql_connect(). If you pass it a file path, ie. /var/run/mysqld/mysqld.sock
, it's going to attempt a socket connection. If you pass it a hostname, it will attempt a TCP connection.
You need to find the hostname (or IP) of the mysql server, and connect to it like this:
mysql_connect('127.0.0.1:3306',$username,$password);
Odds are for ZF, you can just specify this in the configuration file where you store your database settings, or when you connect to the database using the host
setting:
$db = new Zend_Db_Adapter_Pdo_Mysql(array(
'host' => '127.0.0.1',
'username' => 'webuser',
'password' => 'xxxxxxxx',
'dbname' => 'test'
));
Edit: If you are passing a proper hostname/port as the host parameter to mysql_connect()
and getting this message, then it is most likely a server configuration issue.
Try adjusting the mysql.default_socket
setting, either in php.ini or at the top of your application code using ini_set()
ini_set('mysql.default_socket','/path/to/real/socket.sock');
You'll have to figure out where the socket file is. Often it's '/var/lib/mysql/mysql.sock', but I think it's system dependent.
Zend Framework has option in db params unix_socket
, simply use it
$config= array(
'db' => array(
'host' => 'localhost',
'username' => 'user',
'password' => 'pass',
'dbname' => 'dbname',
'dbprefix' => '',
'unix_socket' => '/var/lib/mysqld/mysqld.sock'
)
);