Creating a database connection class (PDO) and fetch data

前端 未结 2 2003
不知归路
不知归路 2020-12-29 16:35

I am new to OOP, so I am trying to learn how to create classes and use them. Currently I am trying to fetch data from my MySQL table.

To create the connection with M

相关标签:
2条回答
  • IMHO you can just inject the PDO connection into the functions that need it:

    <?php
    
    $dbHandle = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $dbHandle->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // always disable emulated prepared statement when using the MySQL driver
    $dbHandle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    
    function get_all($dbHandle) {
        $sql = "SELECT * FROM information";
        $stmt = $dbHandle->prepare($sql);
        $stmt->execute();
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
    
        return $stmt;
    }
    
    get_all($dbHandle);
    

    If you really think you need some class to access to database (other than PDO) (which you don't need) you would have to extend PDO:

    <?php
    
    class DBConnection extends PDO
    {
        public function __construct()
        {
            parent::__construct("mysql:host=$host;dbname=$dbname", $user, $pass);
            $this->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            // always disable emulated prepared statement when using the MySQL driver
            $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        }
    }
    
    $dbHandle = new DBConnection();
    
    function get_all($dbHandle) {
        $sql  = "SELECT * FROM information";
        $stmt = $dbHandle->prepare($sql);
        $stmt->execute();
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
    
        return $stmt;
    }
    
    get_all($dbHandle);
    
    0 讨论(0)
  • 2020-12-29 17:02

    Maybe change the DBConnections FUNCTION to a __contstruct() function. In addition, you'd need to extend the PDO class to use all the methods within it.

    0 讨论(0)
提交回复
热议问题