刚安装XAMPP运行PHP mysqli代码时出现2002连接错误,求解决
Got it, let's break down why you're seeing that "target machine actively refused" error when trying to connect to MySQL with your PHP code. This is a super common issue with XAMPP, and here are the most likely fixes to check step by step:
1. Make sure the MySQL service is running in XAMPP
First things first—open up your XAMPP Control Panel and look at the MySQL module. If it says "Stopped" instead of "Running", click the Start button to fire it up. Sometimes the service doesn't launch automatically when you start XAMPP, or it might have crashed unexpectedly. This is by far the most frequent cause of this error.
2. Verify your connection details match XAMPP's MySQL setup
Your code uses localhost and an empty password (the XAMPP default), but let's double-check a couple of things:
- Port check: XAMPP's MySQL usually uses port 3306, but if another app is using that port, XAMPP might switch it to something like 3307. To confirm, click the Config button next to MySQL in the control panel, open
my.ini(ormy.cnf), and look for the line starting withport =. If it's not 3306, update your connection code to include the correct port:$conn = new mysqli($servername, $username, $password, "", 3307); // Replace 3307 with your actual port - Try
127.0.0.1instead oflocalhost: Sometimeslocalhostresolves to an IPv6 address (::1) and MySQL isn't configured to listen on IPv6. Swapping$servernameto127.0.0.1can bypass this issue entirely.
3. Check if firewalls/security software are blocking the connection
Your local firewall or antivirus might be preventing PHP from accessing MySQL's port (3306). Try temporarily disabling these tools and running your code again. If it works, you'll need to add an exception for MySQL in your firewall settings to allow incoming/outgoing traffic on port 3306.
4. Confirm the root password is correct
By default, XAMPP's MySQL root user has no password, but if you changed it at some point (maybe via phpMyAdmin), your code's empty password will fail. To check, open phpMyAdmin from the XAMPP control panel, go to the User accounts tab, find the root user for localhost, and verify its password status. If you set a password, update your code's $password variable to match.
Quick test to rule out code issues
Open your command prompt/terminal, navigate to your XAMPP's mysql/bin folder (usually C:\xampp\mysql\bin on Windows), and run:
mysql -u root -p
If you can connect by pressing Enter (since password is empty by default), that means MySQL is working fine and the problem is in your code or connection settings. If you get the same error here, focus on fixing the MySQL service itself.
内容的提问来源于stack exchange,提问作者Gameatro

