A friend of mine (on twitter) sent to me a small piece of code to interface a MySQL database using PHP and Object Oriented Programming
I'm very happy to post it.
Here you are the code:
-
<?php
-
-
class DB {
-
const NAME = 'yourdbname';
-
const USER = 'yourdbuser';
-
const PASSWORD = 'yourdbpassword';
-
const HOST = 'yourdbhost';
-
}
-
-
$conn = mysql_connect(DB::HOST, DB::USER, DB::PASSWORD);
-
mysql_select_db(DB::NAME, $conn);
-
-
if ( !$conn ) {
-
die('Could not connect ' . mysql_error());
-
}
-
-
?>
-
-
or better yet
-
-
<?php
-
-
class DB {
-
const NAME = 'yourdbname';
-
const USER = 'yourdbuser';
-
const PASSWORD = 'yourdbpassword';
-
const HOST = 'yourdbhost';
-
-
private $connection;
-
//more properties here
-
-
public function __construct() {
-
$this->conn = mysql_connect(self::HOST, self::USER, self::PASSWORD);
-
mysql_select_db(self::NAME, $this->connection);
-
-
if ( !$this->connection ) {
-
throw new Exception(mysql_error());
-
}
-
}
-
-
//methods here
-
}
-
-
try {
-
$db = new DB();
-
//method calls here
-
} catch (Exception $e) {
-
echo 'Could not connect ' . $e->getMessage;
-
}
-
-
?>
-
-
Notes:
-
– Constants are static members.
-
– Constants cannot be private. This design constraint is due to reflection.
The author is @desiradaniel