2016-05-06 133 views
0

我正在寫簡單的數據庫連接,當我測試它時,它不起作用。 我做錯了什麼? 文件數據庫:警告:mysqli_query()期望參數1是mysqli,null給出

require_once("config.php"); 

class MySqlDatabase{ 
    private $connection; 

    function __construct(){ 
     $this->open_connection(); 
    } 
    public function open_connection(){ 
     $connection = mysqli_connect(DB_SERVER , DB_USER , DB_PASS , DB_NAME); 
     if(!$connection){ 
      die("Database connection failed:" . mysqli_error($connection)); 
     } 
    } 
    public function query($sql){ 
     $result = mysqli_query($this->connection , $sql); 
     $this->confirm_query($result); 
     return $result; 
    } 
    private function confirm_query($result){ 
     if(!$result){ 
      die("Database query failed: ".mysqli_error($this->connection)); 
     } 
    } 
} 

$database = new MySqlDatabase(); 
$db =& $database; 

比我做的請求:

if(isset ($database)) {echo"true";}else {echo "false";} 

$sql ="INSERT INTO users (id, username, password, first_name, last_name)"; 
$sql .="VALUES (1,'olegsavchuk12','1111','Oleg','Savchuk')"; 
$result = $database->query($sql); 
$sql = "SELECT * FROM users WHERE id=1"; 
$result_set = $database->query($sql); 
$found_user = mysqli_fetch_all($result_set); 
echo $found_user['username']; 

而看到此警告。

+3

'open_connection()'中的'$ this-> connection',而不是'$ connection' –

+1

'$ db = $ database;'會做,不需要僞造'&' –

+0

Mark Ba​​ker thx。你的建議是對的 –

回答

-1

你的代碼是除了遺漏的7級簡單人物清潔:$這個 - > 現在,讓我們重新發布代碼,只是這次加入$這個 - >

<?php 
     require_once("config.php"); 

     class MySqlDatabase{ 
      private $connection; 

      function __construct(){ 
       $this->open_connection(); 
      } 
      public function open_connection(){ 
       // THIS SHOULD READ $this->connection NOT $connection 
       // YOU ARE IN A CLASS REMEMBER ;-) 
       $this->connection = mysqli_connect(DB_SERVER , DB_USER , DB_PASS , DB_NAME); 
       // HERE HAS ALSO THE SAME ISSUE AS ABOVE 
       if(!$this->connection){ 
        // AND EVEN HERE TOO:: 
        die("Database connection failed:" . mysqli_error($this->connection)); 
       } 
      } 
      public function query($sql){ 
       // INCIDENTALLY; YOU DID IT PERFECTLY HERE!!! ;-) 
       $result = mysqli_query($this->connection , $sql); 
       $this->confirm_query($result); 
       return $result; 
      } 
      private function confirm_query($result){ 
       if(!$result){ 
        die("Database query failed: ".mysqli_error($this->connection)); 
       } 
      } 
     } 

     $database = new MySqlDatabase(); 
     $db =& $database; 
相關問題