PDO PHP Connection, Fatal Error

后端 未结 1 1211
盖世英雄少女心
盖世英雄少女心 2021-01-23 03:40

My Connection Class;firstcode.php

class DB_functions {
    public $db;
    function __construct() {
        try{
            $db = new PDO("mysql:localhost;d         


        
相关标签:
1条回答
  • 2021-01-23 03:45

    You're almost there. In your class, you need to change each iteration of $db with:

    $this->db
    

    So your class would look like this:

    class DB_functions {
        public $db;
        function __construct() {
            try{
                $this->db = new PDO("mysql:localhost;dbname=xxx;charset=utf8","xxx","xxx");
                echo 'Connected';
            }catch(PDOException $e){
                print $e->getMessage();
                echo "No Connection";
            }
        }
        function __destruct() {}
    
        public function test(){
    
            $query = $this->db->query("SELECT * FROM User", PDO::FETCH_ASSOC);
            if($query->rowCount()){
                foreach ($query as $row) {
                    print_r($row);
                }
            }
        }
    
    }
    

    As you're referencing the internal class variable. It's only accessible within the class scope and is referenced through $this.

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