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…
function __construct()but all the other methods and
properties are either
publicorprivate– usepublic function__construct()
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.phpdie()in OOP? Do you reallywant to output the error message to
the user? It isn’t secure to do that.
It’s better to throw an
Exceptionand work withtry{}andcatch{}to handle an error -> http://de.php.net/manual/en/language.exceptions.phpAre you really sure you’re getting no error messages at all? Show use your
querymethod… Your code should be fine so far (at least you should get an error on screen withdie()if something is not correct).