G
G
Gennady2016-07-24 21:11:08
MySQL
Gennady, 2016-07-24 21:11:08

Why can't connect to MySQL via socket?

Hello. On Debian Jessie installed Nginx + PHP7-FPM + MariaDB 10. I'm trying to run a test script:

<?php
$mysqli = new mysqli(":/var/run/mysqld/mysqld.sock", "root", "password");
if (mysqli_connect_errno()) {
    printf("Ошибка соединения: %s\n", mysqli_connect_error());
    exit();
}
    printf("Версия сервера MySQL: %s\n", $mysqli->server_info);
$mysqli->close();
?>

I receive in response:
Connection error: php_network_getaddresses: getaddrinfo failed: Name or service not known

I change
$mysqli = new mysqli(":/var/run/mysqld/mysqld.sock", "root", "password");

on the
$mysqli = new mysqli("localhost:/var/run/mysqld/mysqld.sock", "root", "password");

I get:
Connection error: Connection refused

If you write:
$mysqli = new mysqli("localhost", "root", "password");

Then everything is displayed as it should:
MySQL Server Version: 5.5.5-10.1.16-MariaDB-1~jessie

Can you please tell me how to make PHP access the database through a socket? I can't figure out what's wrong.
PS The socket file itself is in place:
# locate mysqld.sock
/run/mysqld/mysqld.sock

# php-fpm7.0 --info | grep .default_socket
mysqli.default_socket => no value => no value
pdo_mysql.default_socket => /var/run/mysqld/mysqld.sock => /var/run/mysqld/mysqld.sock

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Philipp, 2016-07-24
@sferg1985

In fact, you have a socket file located in /run/mysqld/mysqld.sock, and you connect to /var/run/mysqld/mysqld.sock
Plus, we read the documentation , and there the socket is the last parameter.
Part one, make sure the socket file is in the right place. Connect to MySQL and see what you have here:
I have /opt/local/var/run/mariadb-10.0/mysqld.sock there .
So I need to fix php.ini

; я ленивый, поэтому настраиваю все варианты подключений
[MySQL]
mysql.default_socket = /opt/local/var/run/mariadb-10.0/mysqld.sock
[MySQLi]
mysqli.default_socket = /opt/local/var/run/mariadb-10.0/mysqld.sock
[Pdo_mysql]
pdo_mysql.default_socket=/opt/local/var/run/mariadb-10.0/mysqld.sock

After that, your scripts should connect via the socket.
// здесь должно быть соединение через сокет
$mysqli = new mysqli("localhost", "root", "password");
// можно принудительно указать путь к сокету
// я очень не рекомендую так делать, 
// т.к. возможны проблемы с развертыванием ваших скриптов в других окружениях
$mysqli = new mysqli("localhost",  "root", "password", "db", 0, 
                              "/opt/local/var/run/mariadb-10.0/mysqld.sock");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question