I get this error when I try to connect to the mysql database using php mysqli class. Using following code:
$db = new MySQLi("localhost","kamil","*****");
if (mysqli_connect_errno())
{
echo "An error occured. Please try again later.";
exit();
}
password is * for security.
I have created user kamil
with all privileges on external ip address and localhost. When I run: select user,host from mysql.user
it properly displays those two users.
I did some research and used this benchmark: https://stackoverflow.com/a/2183134/1839439 to see what it connects to. As it turns out it is only able to connect to 127.0.0.1
and 127.0.0.1:3306
which is localhost, however when I supply localhost
it throws out this error.
My question is why does it only allow me to connect to DB using localhost ip address and not the name or external ip. Do I need a different host if I want to be able to use mysql on website or if I can use 127.0.0.1
?
EDIT:
hosts
file
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
127.0.1.1 raspberrypi
Mysql user table results for this user:
| kamil | 109.255.177.28 |
| kamil | localhost |
If 'localhost' doesn't work but 127.0.0.1 does. Make sure your local hosts file points to the correct location. (/etc/hosts for linux/mac, C:\Windows\System32\drivers\etc\hosts for windows).
Also, make sure your user is allowed to connect to whatever database you're trying to select.
If it's a PHP issue, you could simply alter the configuration file php.ini wherever it's located and update the settings for PORT/SOCKET-PATH etc to make it connect to the server.
In my case, I opened the file php.ini and did
And it worked straight away. I have to admit, I took hint from the accepted answer by @Joni
When you use just "localhost" the MySQL client library tries to use a Unix domain socket for the connection instead of a TCP/IP connection. The error is telling you that the socket, called
MySQL
, cannot be used to make the connection, probably because it does not exist (error number 2).From the MySQL Documentation:
There are a few ways to solve this problem.
127.0.0.1
instead oflocalhost
when you connect. The Unix socket might by faster and safer to use, though.php.ini
: open the MySQL configuration filemy.cnf
to find where MySQL creates the socket, and set PHP'smysqli.default_socket
to that path. On my system it's/var/run/mysqld/mysqld.sock
.Configure the socket directly in the PHP script when opening the connection. For example:
Please check the following file
The line which bind the host name with ip is probably missing a line which bind them togather
If the given line is missing. Add the line in the file
Could you also check your MySQL database's user table and tell us the host column value for the user which you are using. You should have user privilege for both the host "127.0.0.1" and "localhost" and use % as it is a wild char for generic host name.