2

When I try to make a new instance of a MySQLi object to connect to a local database, I get the following error:

Warning: mysqli::mysqli(): (HY000/2002): No such file or directory in /opt/lampp/htdocs/login_system/php/dbconnect.php on line 9

Here is the code for my file:

<?php
        //Database credentials
        $server   = 'localhost';
        $username = 'root';
        $password = 'root'; //NOT secure, used this as a demo
        $database = 'login';

        //Create the database object
        $db = new mysqli($server, $username, $password, $database);

        //Was there errors?
        if($db->connect_errno > 0)
        {
                die("Error connecting to database " . $database + "\nErrors: " + $db->connect_error);
        }
?>

Any ideas as to why this is happening?

Amal Murali
  • 75,622
  • 18
  • 128
  • 150

1 Answers1

4

You need to connect to "127.0.0.1" instead of "localhost".

There is an explanation here: https://serverfault.com/questions/295285/mysql-cannot-connect-via-localhost-only-127-0-0-1

In short your server is configured so MySQL listens to 127.0.0.1 but not localhost.

Community
  • 1
  • 1
mjsa
  • 4,221
  • 1
  • 25
  • 35