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

PHP中MySQL连接函数无法运行:网站登录系统搭建故障排查

Troubleshooting Your MySQL Connection Issue in userConn.php

Hey there! Let’s work through this MySQL connection problem together—this is a super common issue, so we’ll get it sorted out in no time.

First, let’s fix the basics in your code and add error checking to pinpoint exactly what’s going wrong:

1. Complete & Validate Your Connection Code

Your current mysqli_connect call is cut off. Make sure it includes all four required parameters, plus error checking to reveal specific issues:

<?php
/* Database credentials */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '******************');
define('DB_NAME', 'userinfo');

/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

// Add this error check right after the connection attempt
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>

This error message will tell you exactly why the connection is failing—no more guessing!

2. Double-Check Your Credentials & Setup

Let’s rule out the most common culprits:

  • Password: That masked password is easy to typo—confirm it matches what you set for your MySQL root user.
  • Database Name: Make sure the userinfo database actually exists in your MySQL server. You can check this by running SHOW DATABASES; in the MySQL CLI or phpMyAdmin.
  • MySQL Port: If your MySQL is running on a non-default port (like 3307 instead of 3306), update DB_SERVER to include it: 'localhost:3307'.
  • MySQL Service: Confirm your MySQL server is actually running. On Windows, check the Services app; on Linux/macOS, run sudo systemctl status mysql (or mariadb if you’re using that) in your terminal.

3. Ensure the mysqli Extension is Enabled

Sometimes PHP doesn’t have the mysqli extension turned on. Create a quick test file named phpinfo.php with this code:

<?php phpinfo(); ?>

Run it in your browser and search for "mysqli"—if you don’t see it, you’ll need to edit your php.ini file (uncomment extension=mysqli) and restart your web server.

4. Verify User Privileges

Even if your password is correct, the root user might not have access to the userinfo database. Run these queries in MySQL:

GRANT ALL PRIVILEGES ON userinfo.* TO 'root'@'localhost';
FLUSH PRIVILEGES;

This gives the root user full access to the database you’re trying to connect to.

Once you add the error checking, the output will tell you exactly what’s broken. If you still hit a wall, share that error message and we’ll dive deeper!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:34:46