How do I connect to a mysql database through PHP, running LAMP Ubuntu 14.04

February 12, 2015 5.1k views

I am trying to connect using this code.
$username = 'root';
$password = 'password';
$database = 'localhost';
$mysqli = new mysqli("", $username, $password, $database);
if ($mysqli->connecterrno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect
errno . ") " . $mysqli->connect_error;
I get this error, and I assume that it isn't due to my password being incorrect.
Failed to connect to MySQL: (2002) No connection could be made because the target machine actively refused it.
Is there something I am missing? Same error occurs if I try connecting with new users I make also. I should mention this is a remote connection.

  • Is your database named localhost? I would double-check this value. The reason you are unable to connect to your database is because by default MySQL does not enable remote connections. While your client is on the same server, by using the public IP address the requests are being routed through the public network interface. Instead of:

    $mysqli = new mysqli("", $username, $password, $database);

    You should try:

    $mysqli = new mysqli("localhost", $username, $password, $database);
  • Im getting a blank page.. Any solutions for that

Be the first one to answer this question.