timtamboy63
Active Member
Hey guys,
I'm learning OOP PHP and I created a basic class to help out with database handling.
Here it is, fell free to use and modify it. If you do modify it, it'd be cool if you post here as it would be interesting to see what people have done with it
Anyway:
More on chrixel.com :P
I'm learning OOP PHP and I created a basic class to help out with database handling.
Here it is, fell free to use and modify it. If you do modify it, it'd be cool if you post here as it would be interesting to see what people have done with it
Anyway:
PHP:
//Basic Class to deal with databases, created by timtamboy63
class Database {
protected $dbuser = 'root';
protected $dbpass = 'passwordhere';
protected $dbhost = 'localhost';
protected $dbname;
public $connection;
public $queryresult;
public $query;
public $numrows;
function Database($dbname){
//the constructor function
$this->dbname = $dbname;
}
function connect(){
$this->connection = mysql_connect($this->dbhost, $this->dbuser, $this->dbpass) or die(mysql_error());
mysql_select_db($this->dbname, $this->connection) or die('Database could not be selected, Error: ' . mysql_error());
return true;
}
function disconnect(){
mysql_close($this->connection) or die('Could not close database. Error: ' . mysql_error());
return true;
}
function query($query, $type = 2){
//type can be either 0 which does not do anyhting to it
//it can be 1 which will just sanitize the mysql query with mysql_real_escape_string
//or it can be 2 which will also apply htmlentities(and protect against xss), $this is reccomended for anything that gets stored in the database and displayed later
switch($type){
case 0:
$this->query = trim($query);
$this->queryresult = mysql_query($this->query);
return true;
break;
case 1:
$this->query = mysql_real_escape_string(trim($query));
$this->queryresult = mysql_query($this->query);
return true;
break;
case 2:
$this->query = htmlentities(mysql_real_escape_string(trim($query)));
$this->queryresult = mysql_query($this->query);
return true;
break;
default:
die('Function query in class database used incorrectly. The second argument only accepts the values 0, 1 and 2(default & most secure). Read the source for more information');
return false;
break;
}
}
function fetchArray(){
while($row = mysql_fetch_array($this->queryresult)){
//change this to whatever you want.
print $row['id'] . '
';
}
}
function numRows(){
$this->numrows = mysql_num_rows($this->queryresult);
return $this->numrows;
}
}
/* Example usage:
$phonebook = new Database('Phonebook');
$phonebook->connect();
$query = 'SELECT * FROM phonebook';
$phonebook->query($query);
$phonebook->fetchArray();
$phonebook->disconnect();
*/
?>