更新mysqli驱动后MySQL可连接但mysqli报No such file or directory错误
This error almost always boils down to a mismatch between where PHP expects the MySQL socket file to be and where it actually exists, or using localhost instead of TCP/IP for the connection. Here's how to resolve it step by step:
1. Swap localhost with 127.0.0.1 in your connection code
On macOS, using localhost in mysqli tries to connect via a Unix socket, while 127.0.0.1 forces a TCP/IP connection. This is often the quickest fix. Update your connection line to:
$conn = mysqli_connect('127.0.0.1', 'your_username', 'your_password', 'your_database');
If this works, you can stick with it without modifying config files.
2. Align PHP's mysqli socket path with MySQL's actual socket
If you prefer using sockets, you need to make sure PHP knows where MySQL's socket file is located:
- First, find MySQL's socket path in XAMPP: it's typically
/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock - Open your php.ini file (located at
/Applications/XAMPP/xamppfiles/etc/php.ini) - Search for the line
mysqli.default_socketand set it to the correct path:mysqli.default_socket = /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock - Save the file and restart Apache from the XAMPP control panel.
3. Verify the socket file exists and has correct permissions
Sometimes the socket file might be missing or have restricted access:
- Open Terminal and run this command to check if the socket exists:
ls /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock - If it doesn't exist, ensure MySQL is running in the XAMPP control panel (restart it if needed).
- If permissions are an issue, fix them with:
chmod 755 /Applications/XAMPP/xamppfiles/var/mysql/
4. Ensure the mysqli extension is enabled
Double-check that the mysqli extension isn't commented out in php.ini:
- Open php.ini and look for
extension=mysqli(orextension=mysqli.soon older versions) - Make sure the line doesn't start with a semicolon (
;). If it does, remove the semicolon and restart Apache.
If none of these steps work, try reinstalling XAMPP to ensure all extensions and config files are intact.
内容的提问来源于stack exchange,提问作者Emmanuel agahiu

