2011-01-27 11 views
1

我是OOP的新手,並且在創建數據庫連接時遇到問題,可能是什麼問題?奇怪的是我沒有得到任何錯誤,但我不能做任何MYSQL插入或從數據庫中選擇,因爲連接尚未取得使用對象進行數據庫連接

//include the file that contains variables necessary for database connection 
require_once 'configurations.php'; 

//This is the class that will be used for the MySQL Database transactions 
class MySQLDatabase 
{ 
    private $database_connection; 

    //constructor class 
    function __construct() 
    { 
     $this->open_connection(); 
    } 

    public function open_connection() 
    { 
     $this->database_connection = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD); 
     if (!$this->database_connection) 
     { 
      //if the connection fails, return the following message and indicate the error 
      die("Could not connect to the MYSQL Database due to: " . mysql_error()); 
     } 
     else 
     { 
      //if the connection is made to MYSQL database, then select the database being used 
      $database_selection = mysql_select_db(DATABASE_NAME, $this->database_connection); 

      //if the database to be used cannot be selected, return this error 
      if (!$database_selection) 
      { 
       die ("Could not select the database due to: " . mysql_error()); 
      } 
     } 
    }//end of function open database 
}//end of class MySQLDatabase 

$database_transactions = new MySQLDatabase(); 
+2

您是否收到任何錯誤訊息?你在試圖告訴你它不工作? – 2011-01-27 06:13:29

回答

2

有幾件事情我會考慮...

  • 你寫function __construct() 但所有的其他方法和 屬性是可publicprivate - 使用public function __construct()
  • 爲什麼是方法open_connection() 公共?是否應該從 「外部」調用?你想有人 從一個對象直接執行這個方法 ?想一想吧private function open_connection() - >http://de.php.net/manual/en/language.oop5.visibility.php
  • 爲什麼在OOP中使用die()?你真的 想輸出錯誤信息給 的用戶嗎?這樣做不安全。 這是更好地拋出Exceptiontry{}catch{}工作處理錯誤 - >http://de.php.net/manual/en/language.exceptions.php

你真的確定你得到完全沒有錯誤信息?顯示使用你的query方法...你的代碼應該沒問題(至少你應該在屏幕上出現一個錯誤,如果有不正確的東西,你應該輸入die())。

相關問題