You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:PHP MySQLi连接报错(HY000/2002)及无法获取mysqli问题

Fixing MySQLi Connection Errors (HY000/2002)

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.php file with this code: <?php phpinfo(); ?>
  • Run it in your browser and look for the mysqli.default_socket value (e.g., /run/mysqld/mysqld.sock on 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 root password correct? Your script uses an empty password—double-check that matches your server's setup.
  • Does the dbproject database 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:31:49