Search code examples
phpmysqlconnectionlamp

Connection failed: Connection refused mysql (LAMP)


When I try to connect to mysql it refuses my script. I have mysql installed on ubuntu 16.10 (LAMP).

When I run this:

<?php
$servername = "ip";
$username = "user";
$password = "pw";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
?>

It shows:

Connection failed: Connection refused mysql (LAMP)

I tried to change the bind-address to 0.0.0.0, then it showed:

Connection failed: Host 'webserver1' is not allowed to connect to this MySQL server

I tried to comment (#) the bind-address. That didn't work either.

I am running the scripts on a client with another ip-range/subnet then the mysql-server. When I run phpmyadmin on the client I have no problem.


Solution

  • Its possible to have a security precaution. You could try adding a new administrator account in mysql.

    mysql> CREATE USER 'yourUser'@'localhost' IDENTIFIED BY 'some_pass';
    mysql> GRANT ALL PRIVILEGES ON *.* TO 'yourUser'@'localhost'
        ->     WITH GRANT OPTION;
    mysql> CREATE USER 'yourUser'@'%' IDENTIFIED BY 'some_pass';
    mysql> GRANT ALL PRIVILEGES ON *.* TO 'yourUser'@'%'
        ->     WITH GRANT OPTION;
    

    Try newly created user in your code.

    Hope it helps!