MySQL using OO PHP
Posted: Sun Jul 12, 2009 10:55 am
This is my first attempt at object-oriented PHP coding, so any critique would be appreciated. I've tested the code and know that it works, but I'm unsure about whether or not the style is good or bad (am I going against best practices?).
Note: After reading the Coding Critique post, I've followed the advice and updated this first post with the newest copy of the code.
Note: After reading the Coding Critique post, I've followed the advice and updated this first post with the newest copy of the code.
Code: Select all
<?php
class MySQL {
private $connection;
public function __construct($array = false) {
if (!is_array($array)) {
$array = array(
0 => 'hostname',
1 => 'username',
2 => 'password',
3 => 'database',
);
}
$this->connect($array);
}
private function connect($array) {
$this->connection = @mysql_connect($array[0], $array[1], $array[2]);
if (!empty($array[3])) {
$this->database($array[3]);
}
}
public function connected() {
return is_resource($this->connection);
}
public function database($database) {
if (!$this->connected()) {
return false;
}
return @mysql_select_db($database, $this->connection);
}
public function query($query) {
if (!$this->connected()) {
return false;
}
return new MySQLResult(@mysql_query($query, $this->connection));
}
public function disconnect() {
if (!$this->connected()) {
return false;
}
return @mysql_close($this->connection);
}
}
class MySQLResult {
private $result;
public function __construct($result) {
$this->result = $result;
}
public function fetch() {
if (!is_resource($this->result)) {
return false;
}
return @mysql_fetch_assoc($this->result);
}
}
?>