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

基于自定义PDO数据库连接类的数据获取问题求助

Hey there! Let's fix up how you use your custom PDO class to fetch data from your database. First, let's address a couple of small issues in your existing dbconnect class, then walk through the correct way to run your query.

1. Fix the Custom PDO Class

Since you're extending the native PDO class, you don't need a separate $dbh property—your dbconnect instance is a PDO connection. Also, we'll add proper error handling to make debugging easier:

class dbconnect extends PDO {
    private $dbengine = 'mysql';
    private $dbhost = 'localhost';
    private $dbuser = 'root';
    private $dbpassword = 'root';
    private $dbname = 'nesiojami';

    public function __construct() {
        try {
            // Call the parent PDO constructor to initialize the connection
            parent::__construct(
                "$this->dbengine:host=$this->dbhost;dbname=$this->dbname",
                $this->dbuser,
                $this->dbpassword
            );
            // Set default fetch mode (you had this right!)
            $this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
            // Enable exception-based error handling (critical for debugging)
            $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            // Throw a meaningful error instead of silently failing
            throw new Exception("Database connection failed: " . $e->getMessage());
        }
    }
}

2. Use the Class to Fetch Data

Now that the class is fixed, here's how to execute your query correctly. Important note: Your field names have hyphens (client-name, client-surname), so you need to wrap them in backticks ` to avoid MySQL parsing errors (it would otherwise interpret client-name as client - name):

// Create an instance of your custom connection class
$db = new dbconnect();

try {
    // Run the query (note the backticks around field names)
    $stmt = $db->query("SELECT `client-name`, `client-surname` FROM clients");
    // Fetch results as an associative array (overrides the default FETCH_OBJ)
    $clients = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Check out your data!
    print_r($clients);
} catch (PDOException $e) {
    echo "Query failed: " . $e->getMessage();
}

Key Takeaways

  • When extending PDO, your class inherits all PDO methods directly—no need to use a separate $dbh property.
  • Always wrap field/table names with special characters (like hyphens) in backticks to avoid syntax errors.
  • Enabling PDO::ERRMODE_EXCEPTION ensures you get clear error messages instead of silent failures, which makes debugging way easier.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:46:29