求助:PHP MySQLi连接报错(HY000/2002)及无法获取mysqli问题
Hey there! Let's work through these errors step by step. The root problem here is your script can't establish a connection to the MySQL server—all the follow-up errors on lines 7 and 23 are just side effects of that failed initial connection.
What's causing the "No such file or directory" error?
When you use localhost as the host in MySQLi, PHP tries to connect using a Unix socket file instead of standard TCP/IP. If that socket file doesn't exist in the location PHP expects (super common on systems like Synology NAS, given your /volume1/web path), you get this exact error.
Quick Fixes to Try
1. Force TCP/IP Connection (Simplest Solution)
Replace localhost with 127.0.0.1 in your connection line. This tells PHP to skip the socket file and use TCP/IP directly, which avoids the "no such file" issue:
<?php // Connect to the DB $mysqli = NEW MySQLi("127.0.0.1","root","","dbproject"); // Add a connection check first to catch issues early if ($mysqli->connect_error) { die("Connection failed: " . $mysqli->connect_error); } //Query the DB $resultSet = $mysqli->query("SELECT * FROM clients"); // Count the returned rows if($resultSet->num_rows != 0) { while($rows = $resultSet->fetch_assoc()) { $id = $rows['id']; $fname = $rows['firstname']; $lname = $rows['lastname']; $country = $rows['country']; echo "<p>ID: " .$id. " <br /> Name: ".$fname." ".$lname. "<br /> Country: ".$country." </p>"; } } else{ echo "No records found in the clients table."; } // Clean up the connection when done $mysqli->close(); ?>
2. Specify the Correct Socket Path
If you need to keep using localhost, you'll need to point PHP to the actual location of your MySQL socket file:
- Create a temporary
phpinfo.phpfile with this code:<?php phpinfo(); ?> - Run it in your browser and look for the
mysqli.default_socketvalue (e.g.,/run/mysqld/mysqld.sockon Synology) - Add that socket path to your connection line:
$mysqli = NEW MySQLi("localhost","root","","dbproject", null, "/path/to/your/mysqld.sock");
Additional Checks to Rule Out Other Issues
Don't forget to verify these basics too:
- Is the MySQL/MariaDB service actually running on your server?
- Is the
rootpassword correct? Your script uses an empty password—double-check that matches your server's setup. - Does the
dbprojectdatabase exist? You can confirm this via phpMyAdmin or the MySQL command line.
Once you fix the connection problem, the errors on lines 7 and 23 will disappear automatically—they only happen because the $mysqli object wasn't created successfully.
内容的提问来源于stack exchange,提问作者R. Bos

