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

PHP PDO无法连接数据库:创建注册页遇未知数据库错误求助

Fixing Your Database Connection & Query Errors

Alright, let's tackle these two linked errors you're facing—they're directly connected, so fixing the root cause will resolve both issues.

1. Resolving SQLSTATE[HY000] [1049] Unknown database 'site'

This error is straightforward: the database named site doesn't exist in your MySQL server yet. Here's how to fix it:

  • Fire up XAMPP, make sure the MySQL service is running, then open phpMyAdmin (usually at http://localhost/phpmyadmin).
  • In phpMyAdmin, click the "Databases" tab at the top.
  • Under "Create database", enter site exactly as it appears in your code (note: MySQL is case-sensitive on Linux, so match the spelling/case perfectly), then click "Create".
  • Double-check your PDO connection code in PDOMain.class.php to ensure the dbname parameter is set to site—no typos allowed!

2. Fixing Call to a member function query() on null

This fatal error happens because your PDOMain class's database connection failed (due to the missing database above), so the PDO object is null when you try to call query() on it. To fix this and prevent future issues:

  • First, ensure the database connection code in PDOMain.class.php includes proper error handling. A solid connection setup should look like this:
class PDOMain {
    private $pdo;

    public function __construct() {
        try {
            // Update these values to match your XAMPP MySQL credentials
            $this->pdo = new PDO(
                'mysql:host=localhost;dbname=site;charset=utf8mb4',
                'root', // Default XAMPP MySQL username
                ''      // Default XAMPP MySQL password (empty string)
            );
            // Enable exceptions for easier debugging
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            die("Database connection failed: " . $e->getMessage());
        }
    }

    // Your selectPDO method here...
}
  • Verify that your selectPDO method only uses $this->pdo after the connection is successfully established (the constructor above ensures this if no exception is thrown).
  • If you've changed your XAMPP MySQL username/password from the defaults, update those values in the PDO constructor.

Quick Post-Fix Checks

After creating the database and updating your connection code:

  • Restart the MySQL service in XAMPP to ensure changes take effect.
  • Test your registration page again—both errors should be gone if everything is set up correctly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:28:42