如何使用面向对象结构在PHP中运行PDO数据库连接


How can run PDO database connection in PHP with OOP structure?

考虑以下PHP编码。。。

<?php
class MyPDO extends PDO{
    const PARAM_host='localhost';
    const PARAM_port='3306';
    const PARAM_db_name='test';
    const PARAM_user='root';
    const PARAM_db_pass='';
    public $con;
    public function __construct(){
        $user = MyPDO::PARAM_user;
        $password = MyPDO::PARAM_db_pass;
        $dsn = 'mysql:host='.MyPDO::PARAM_host.';port='.MyPDO::PARAM_port.';dbname='.MyPDO::PARAM_db_name;
        try {
            $con = new PDO($dsn, $user, $password);
            echo "connected successfully";
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }
    } //End of constructor function

    public function fetch(){
        // Fetch Data form Table
        try{
            /*** The SQL SELECT statement ***/
            $sql = "SELECT * FROM student";
            foreach ($con->query($sql) as $row)
                {
                print $row['Roll'] .' - '. $row['Name'] . '<br />';
                }
        }
        catch(PDOException $e){
            echo $e->getMessage();
            }
    }//End of function Fetch
} //End of class
$obj = new MyPDO;
$obj->fetch();
?>

如果我运行上述编码,则显示以下错误消息:-

注意:第33行C:''examplep''htdocs''php''11.php中的未定义变量:con

致命错误:在第33行的C:''examplep''htdocs''php''11.php中,对非对象调用成员函数query()

上面的代码段会有什么变化?

由于con是一个成员变量,因此使用以下语法来引用它:

$this->con = ... 
$this->con->query($sql)

由于您在Class对象上下文中,请使用以下内容:

$this->con = new PDO($dsn, $user, $password);
$this->con->query("Your sql query");