2014-07-21 33 views
0

我想通過查詢測試數據庫來學習OOP PHP。我試着用Google搜索答案,但無濟於事。這是我的代碼:OOP PHP未定義變量和空查詢

<?php 

class DB { 

     protected $db; 
     protected $query; 

     public function __construct() { 
      $this->db = new mysqli("localhost","root","","test2"); 
      $this->query = "SELECT * FROM test"; 
     } 


     public function querydb() { 
      $this->db->query($db,$query); 
     } 

    } 

    $database = new DB(); 
    $database->querydb(); 


?> 

它說構造函數中定義的兩個變量沒有定義,並且查詢是空的。有什麼建議麼?

+0

我理解查詢($分貝,$查詢)部分可能是壞的。如果對不起,這是我第五次重寫這段代碼。 – user2941726

+1

你能給我們確切的錯誤信息嗎? –

+0

你也可以顯示你啓動數據庫類的代碼嗎?如果你想進一步處理它,querydb()函數應該返回查詢結果 – KhorneHoly

回答

1

變化:

$這個 - > DB->查詢($分貝,$查詢);

到:

$這 - > DB->查詢($這個 - >查詢);

試試這個:

<?php 

class DB { 

     protected $db; 
     protected $query; 

     public function __construct() { 
      $this->db = new mysqli("localhost","root","","test2"); 
      $this->query = "SELECT * FROM test"; 
     } 


     public function querydb() { 
      $this->db->query($this->query); 
     } 

    } 

    $database = new DB(); 
    $database->querydb(); 


?> 
+1

'$ this-> db'也是,不僅'$ this-> query' – Sugar

+0

是的,你是對的 –

+0

這擺脫了我所有的3個錯誤信息。但現在它說:**警告:mysqli :: query()期望參數1是字符串,對象在第37行的/opt/lampp/htdocs/test/index.php中給出; ** – user2941726

0

您試圖在querydb方法使用一些未定義的局部變量。將它們替換爲類字段。

替換:

public function querydb() { 
    $this->db->query($db,$query); 
} 

有:

public function querydb() { 
    $this->db->query($this->db, $this->query); 
} 
0
public function querydb() { 
     $this->db->query($this->query); 
    } 

你應該使用$this->query代替$query

0

變化

可參照查詢

public function querydb() { 
      $this->db->query($this->db,$this->query); 
     }