Fatal error: Call to a member function query() PHP CLASS

前端 未结 2 475
花落未央
花落未央 2021-01-15 19:20

I\'m trying to write this class to connect and query my database, but I got this error:

Fatal error: Call to a member function query() on null in C:

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-15 19:48

    Your method:

    public function db_connect() {    
    
                $connection = mysqli_connect(self::$db_host, self::$db_user, self::$db_pass, self::$db_name) or die("Error " . mysqli_error($connection)); 
                echo "Conexión realizada". "
    "; }

    does not retun the $connection back from the method so the rest method calls fail do this:

    public function db_connect() {    
    
                $connection = mysqli_connect(self::$db_host, self::$db_user, self::$db_pass, self::$db_name) or die("Error " . mysqli_error($connection)); 
                echo "Conexión realizada". "
    "; return $connection; // return the $connection object }

    As mentioned, your code is not efficient since for every query performed the code (re-)connects to the DB. THis is unnecessarily expensive/inefficient.

    There are many approaches to solve this.

    1. Connect to the DB on the instantiation of the DB class

    e.g

    class Db{
    
        private static $db_host = "localhost";
        private static $db_user = "root";
        private static $db_pass = "";
        private static $db_name = "sivi";
    
        public $connection;
    
        public function __construct()
       {
          $this->connection = $this->db_connect();
       }  
    
        public function db_connect() {    
    
                $connection = mysqli_connect(self::$db_host, self::$db_user, self::$db_pass, self::$db_name) or die("Error " . mysqli_error($connection)); 
                echo "Conexión realizada". "
    "; return $connection; } }
    1. Lazy connection, i.e connect only on first executed query

    e.g

    class Db{
    
        private static $db_host = "localhost";
        private static $db_user = "root";
        private static $db_pass = "";
        private static $db_name = "sivi";
        public $connection = null;
        public function __construct()
        {
        }  
        public function db_connect() {    
            $connection = mysqli_connect(self::$db_host, self::$db_user, self::$db_pass, self::$db_name) or die("Error " . mysqli_error($connection)); 
            echo "Conexión realizada". "
    "; return $connection; } public function db_query($query){ if ( null ==== $this->connection ) $this->connection = $this->db_connect(); var_dump($query); $result = $this->connection->query($query); while($row = mysqli_fetch_array($result)) { echo $row["COD_PRE"] . "
    "; } } }

提交回复
热议问题