Connect PHP to mysql server running on Mac [duplicate]

  mysql, php

I am trying to connect to my MySQL server on a mac using PHP after starting the server using brew services start mysql After this I can see that the MySQL server has successfully started. However, when I try to access my webpage using:


/* Attempt to connect to MySQL database */
$link = mysqli_connect('localhost', 'root', 'password', 'databasename');
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());

The webpage start spinning continuously and doesn’t load. I was wondering what’s the issue as I can log into the root from the command line as well as see the tables. And the bre shows MySQL server running in the background.

EDIT I managed to print my error however, now I get an error:

Warning: mysqli_connect(): (HY000/2002): No such file or directory However, homebrew shows my MySQL server running.

Source: Ask PHP