2011-01-27 41 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())。