开发者

Using an object for database connections

I am new to OOP having this code and am having a problem creating a database connection, what could be the problem? Strangely am not getting any errors yet i cannot make any MYSQL INSERTS or SELECTS from the database because the connections have not been made

    //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();


There are a few things I would consider...

  • You write function __construct() but all the other methods and properties are either public or private - use public function __construct()
  • Why is the method open_connection() public? Should it be called from "outside"? Do you want someone to execute this method directly from an object? Think about making it private function open_connection() -> http://de.php.net/manual/en/language.oop5.visibility.php
  • Why use die() in OOP? Do you really want to output the error message to the user? It isn't secure to do that. It's better to throw an Exception and work with try{} and catch{} to handle an error -> http://de.php.net/manual/en/language.exceptions.php

Are you really sure you're getting no error messages at all? Show use your query method... Your code should be fine so far (at least you should get an error on screen with die() if something is not correct).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜