mySQL Class
Original posted by: Admin on 01-02-2007
If you look through the other functions under the mySQL category you will notice they are all function based code, which is nice because they can be thrown into a class and utilized quiet well.
Lets start by making a class with the three major functions, read, write and connect.
class mySQL {
function mySQL($host = 'localhost', $username = 'username', $password = 'password', $database = 'database') {
//Conntect to the mySQL
$link = mysql_connect($host, $username, $password);
if(!$link)
return 'Could not connect: ' . mysql_error();
else {
$db_selected = mysql_select_db($database, $link);
if (!$db_selected)
die ('Could not use '.$database.': ' . mysql_error());
return true;
}
}
function readDB($query) {
$result = mysql_query($query) or die(mysql_error());
if(!$result) {
return false;
} else {
$i = 0;
while($row = mysql_fetch_assoc($result)) {
foreach($row as $node => $key)
$return[$i][$node] = $key;
$i++;
}
}
mysql_free_result($result);
return $return;
}
function writeDB($query) {
mysql_query($query) or die(mysql_error());
return mysql_insert_id();
}
}
Now all you have to do to connect to the database is;
$db = new mySQL();
To read something;
$db->readDB('SELECT * FROM `foo` WHERE 1=1');
To write something;
$db->writeDB('INSERT INTO `foo` (`col1`, `col2`) VALUES ('foo1', 'foo2')');