PHP mysqli_connect() Error on "localhost"

This section provides a tutorial on the PHP mysqli_connect() 'No such file or directory' error, and the workaround of replacing 'localhost' with '127.0.0.1'.

If you try to connect the MySQL server on the local macOS system with "localhost" as the server name, using PHP mysqli_connect() function, you may get the "No such file or directory" error.

Here is the my PHP test script, MySQL-Localhost.php:

%lt;?php
#  MySQL-Localhost.php
#- Copyright (c) 2009 HerongYang.com, All Rights Reserved.
#
   $con = mysqli_connect('localhost','guest','guest');
   print "MySQL server info = ".mysqli_get_server_info($con)."\n";
   print "MySQL status = ".mysqli_stat($con)."\n";
   mysqli_close($con);
?>

Here is the error message I got, when running it to reach the MySQL server on my local macOS computer:

herong$ php MySQL-Localhost.php
PHP Warning:  mysqli_connect(): (HY000/2002): No such file or directory in \
   /Users/herong/MySQL-Localhost.php on line 6
...

One way to avoid this error is to use the IP address representing the "localhost". You can find the IP address of "localhost" with the "ping" command:

herong$ ping localhost

PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.046 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.065 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.071 ms
^C

Update the PHP test script with the IP address:

<?php
#  MySQL-IP.php
#- Copyright (c) 2009 HerongYang.com, All Rights Reserved.
#
   $con = mysqli_connect('127.0.0.1','guest','guest');
   print "MySQL server info = ".mysqli_get_server_info($con)."\n";
   print "MySQL status = ".mysqli_stat($con)."\n";
   mysqli_close($con);
?>

The updated script should work now:

herong$ php MySQL-IP.php

MySQL server info = 8.0.17
MySQL status = Uptime: 180642  Threads: 11  Questions: 299593
   Slow queries: 0  Opens: 728  Flush tables: 3  Open tables: 609
   Queries per second avg: 1.658

Table of Contents

 About This Book

 Macintosh OS (Operating System) History

 macOS Operating System

 macOS File Systems

 macOS Network Connections

 System and Application Processes

 Keychain Access - Password Manager

 Keychain Access - Certificate Manager

 Productivity Tools on macOS

Programming Tools on macOS

 Run Perl Scripts on macOS

 Install File::Util for Perl

 Run Python Scripts on macOS

 Install New Version of Python on macOS

 pip3 - Package Installer for Python 3

 Run PHP Scripts on macOS

 Install MySQL Database Server on macOS

PHP mysqli_connect() Error on "localhost"

 Install SQuirreL SQL Client on macOS

 Connect SQuirreL to MySQL on macOS

 Install SQuirreL SQL Scripts Plugins

 Apache Web Server on macOS

 Develop and Run Java Applications

 Full Version in PDF/EPUB