Connecting to MySQL Database through Terminal: Fix for "No such file or directory" Error
The "Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in" error occurs when a PHP script attempts to establish a connection to a MySQL database via the terminal but cannot locate the socket file.
To resolve this issue, the problem lies in the location of the socket file. On macOS, MySQL may have an incorrect configuration for the socket file path. Here's how to fix it:
Step 1: Determine the Socket File Location
Use the following command to check the socket file locations:
ls -l /tmp/mysql.sock /var/mysql/mysql.sock
Step 2: Create a Symbolic Link
Depending on the location of the existing socket file, create a symbolic link using one of the following commands:
If you have /tmp/mysql.sock but no /var/mysql/mysql.sock
cd /var sudo mkdir mysql sudo chmod 755 mysql cd mysql sudo ln -s /tmp/mysql.sock mysql.sock
If you have /var/mysql/mysql.sock but no /tmp/mysql.sock
cd /tmp ln -s /var/mysql/mysql.sock mysql.sock
Step 3: Run Script
After creating the symbolic link, run your PHP script using the following command:
php scriptname.php
This should now successfully connect to the MySQL database. Note that you may need to adjust the file paths in your PHP script to point to the correct location of the socket file.
The above is the detailed content of How to Fix the 'No such file or directory' Error When Connecting to MySQL via Terminal?. For more information, please follow other related articles on the PHP Chinese website!