Had a very frustrating day as I’ve been trying to set up a local environment to code some PHP. I was using MAMP to make it quite simple. I could connect to the database on terminal but not by calling the mysqli_connect(). Adding these two lines of code helped find the problem:
When these two lines of code were added, I was able to see the following error message:
mysqli_connect():  No such file or directory (trying to connect via unix:///var/mysql/mysql.sock) in /Library/WebServer/Documents/connect/index.php on line 6 Warning: mysqli_connect(): (HY000/2002): No such file or directory in /Library/WebServer/Documents/connect/index.php on line 6
I never really did find a fix, but I found a deeper problem. I was putting files in the localhost directory and they were being executed fine. However, I then realised that the environment MAMP had created was in fact accessible by including the port, i.e. localhost:8888/. Shutting down the apache and mysql server with MAMP, I loaded up my files in locahost and confirmed what I knew, something else was executing them. I must have some old legacy servers running in the background I figure. Either way, I gave up.
Got a shiny brand new Macbook Air. Within 5 minutes I was able to connect to mysql in both terminal and by calling mysqli_connect(). The default password is root for MAMP, so when you change it with the command
mysqladmin -u root -p password "newpassword"
Make sure that you update the new password in the two following locations
If you don’t do the latter you’ll receive an error saying it can’t connect to the mysql database. All in all quite a frustrating experience today. I’d prefer to code on the iMac but ultimately the stress associated to have a ‘clean start’ will be rather annoying.