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

PHP连接MySQL时出现未捕获PDOException错误求助

Fixing "Access denied for user 'root'@'localhost' (using password: NO)" in PDO PHP Connection

Hey there, let's walk through fixing this common database connection error. The error message spells out exactly what's going wrong: your PHP code is trying to connect to MySQL as the root user without providing a password, but MySQL is rejecting that request. Here's how to resolve it step by step:

1. Check your PDO connection code first

Open up your config.php file (line 7 is where the error originates). Your connection line probably looks something like this:

$pdo = new PDO('mysql:host=localhost;dbname=your_database_name', 'root', '');

The third parameter here is an empty string—meaning you're not passing a password to MySQL.

  • If you set a password for your MySQL root user when setting up XAMPP, replace that empty string with your actual root password:
    $pdo = new PDO('mysql:host=localhost;dbname=your_database_name', 'root', 'your_root_password');
    
  • If you never set a password for root, skip to step 2 to rule out other potential issues.

2. Verify your MySQL root user can log in

Let's confirm your root user has valid access to MySQL:

  • Open the XAMPP Control Panel and make sure the MySQL service is running (click "Start" if it's stopped).
  • Launch the MySQL Shell (from XAMPP or your terminal) and run:
    mysql -u root -p
    
    • If it asks for a password and you can log in successfully, use that exact password in your PDO code.
    • If it logs you in without asking for a password, your root user has no password—so the empty string in your code should work, but we need to check the connection host next.

3. Try using 127.0.0.1 instead of localhost

Sometimes MySQL treats localhost (a socket-based connection) differently from 127.0.0.1 (a TCP/IP connection). Update your connection string to:

$pdo = new PDO('mysql:host=127.0.0.1;dbname=your_database_name', 'root', 'your_password');

4. Fix MySQL user privileges (if all else fails)

If you're still hitting the error, it might be a permission issue within MySQL. Log into MySQL as root and run these commands:

-- Check existing root users and their associated hosts
SELECT user, host FROM mysql.user;

-- If 'root'@'localhost' doesn't exist or has limited access, grant full privileges
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'your_password';
FLUSH PRIVILEGES;

This ensures the root user has all necessary permissions to connect from your local machine.

Once you make these adjustments, save your config.php file and reload your registration page—it should connect to the database successfully!

内容的提问来源于stack exchange,提问作者Abdullah Juma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 18:32:34