2014-12-26 81 views
1

下面是使用(試圖)從數據庫中提取信息但它給我一個錯誤的文件。PHP數據庫類錯誤

配置文件:

define("DBHOST", "127.0.0.1"); 
define("DBUSER", "root"); 
define("DBPASS", "root"); 
define("DBNAME", "test"); 
define("DBPORT", "3306"); 

DB類:

class Database{ 

    public function __contruct(){ 
     $con = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME, DBPORT); 

     if (!$con){ 
      die("Error connecting to database"); 
     } 
     else{ 
      $this->con = $con; 
     } 
    } 

    function SimpleQuery(){ 
     $query="SELECT * FROM accounts"; 
     $array = $this->con->query($query); 
     while ($fields = $array->fetch_array(MYSQL_ASSOC)){ 
      $values[] = $fields; 
     } 
     return $values; 
    } 
} 

索引文件:

require ("config.php"); 
require ("database.php"); 

$db = new Database(); 

echo $rows = $db->SimpleQuery(); 

給了我這個錯誤:

Fatal error: Call to a member function query() on a non-object in database.php 
+1

我認爲你應該在課堂中聲明$ con。 http://php.net/manual/en/language.oop5.properties.php –

+0

這些東西沒有工作:( – Phentom

+0

@Phentom這是一個錯字,你有'__contruct'而不是'__construct'。另外,你應該檢查對於連接錯誤,使用'$ this-> con> connect_errors'(給出更多細節爲什麼連接失敗) – Bjorn

回答

0

你在CON 2半個冒號= DB類

+0

複製錯誤,我的錯誤 – Phentom

0

的聲明試試這個:

DB類:

class Database{ 

    public function __construct(){ 
         //^problem here 
     $con = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME, DBPORT); 

     if (!$con){ 
      die("Error connecting to database"); 
     } 
     else{ 
      $this->con = $con; 
     } 
    } 

    function SimpleQuery(){ 
     $query="SELECT * FROM accounts"; 
     $array = $this->con->query($query); 
     while ($fields = $array->fetch_array(MYSQL_ASSOC)){ 
      $values[] = $fields; 
     } 
     return $values; 
    } 
} 

索引文件:

<?php 
//error_reporting(E_ALL); 
//ini_set('display_errors',1); 
include("submit.php"); 

$db = new Database(); 
$rows = $db->SimpleQuery(); 
print_r($rows); 
+0

不起作用= S – Phentom

+0

@Phentom嘗試更新一個。 –