<?php
class MySqlDatabase {
var $connection;
function MySqlDatabase($database,$user,$password,$host='localhost',$log=false){
$this->database = $database;
$this->user = $user;
$this->password = $password;
$this->host = $host;
$this->error_file = $log;
}
/* connects to the database if not already done */
function connect(){
if(!$this->connection){
$this->connection = mysql_connect($this->host,$this->user,$this->password)
or $this->error("Error in connect() with user {$this->user} host {$this->host} database {$this->database}" + mysql_error());
mysql_select_db($this->database, $this->connection)
or $this->error(mysql_error());
}
}
/* executes a sql statment */
function sql($sql){
$this->connect();
$this->result = mysql_query($sql, $this->connection) or $this->error(mysql_error() . "\n\t$sql");
return $this->result;
}
/* escapes dangerous strings to make them safe - takes an array of values */
function escape_array($data){
$this->connect();
foreach($data as $row => $value){
if(is_array($value)) {
$data[$row] = $this->escape_array($value);
} else if(is_string($value)) {
$data[$row] = mysql_real_escape_string($value,$this->connection);
}
}
return $data;
}
/* excapes a single string # MUST FIX THIS TYPO # */
function excape($string){
return $this->escape($string);
}
/* escapes a single string */
function escape($string){
$this->connect();
return mysql_real_escape_string($string,$this->connection);
}
/* results the insert id of the last query */
function insert_id(){
return mysql_insert_id($this->connection);
}
/* returns a row and changes pointer to next */
function get_row($result=false){
if($result){
return mysql_fetch_assoc($result);
} else {
return mysql_fetch_assoc($this->result);
}
}
/* returns the number of rows returned by a query */
function num_rows($result=false){
if($result){
return mysql_num_rows($result);
} else {
return mysql_num_rows($this->result);
}
}
/* writes and error to a file */
function error($error){
if($this->error_file){
if(!$handle = fopen($this->error_file, 'a')) {
trigger_error("Cannot open file ($this->errorFile)", E_USER_ERROR);
}
if(fwrite($handle, $error."\n") === FALSE) {
trigger_error("Cannot write to file ($this->errorFile)", E_USER_ERROR);
}
fclose($handle);
}
die('<p>An error occurred in the database, please check the error log.</p>');
}
}
?>