473,396 Members | 1,927 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

database class

Hi Folk

What do you think about this database class? Do you have any feedback
or ideas on how it could be improved?

Thank you

Nicolaas

class dbClass {
/*
const = costant
private = only available within class
protected = only available within class and related classes
to force to slave (if appropiate), choose "false" for
overideToMaster variable
enter values below
*/
public $errorString, $debug;
protected $firstWord, $databaseLink;
private $timeCriticalTablesArray = array("temp2"); // tables that
should always be done on the master
private $databaseArray = array(
"MASTER" =array("serverName"=>'xxx', "username"=>'xxx-1',
"password"=>'xxx', "databaseName"=>'xxx-1'),
"SLAVE" =array("serverName"=>'xxx', "username"=>'xxx-2',
"password"=>'xxx', "databaseName"=>'xxx-2')
);
private $sqlFirstWordIsSafeArray = array("SELECT"); //THESE HAVE TO
BE UPPERCASE!!!!!!!!!!!!!
private $masterDigitsArray = array(0,2,4,6,8); //change the ratio
between servers - the more numbers, the more work for the master
const maxTries = 3; //number of connection tries before an error is
returned
//initialisation, debugging and destruction
function __construct() {
$this->debugLine .= 'Starting DB class:<hr />';
}
function __destruct() {
//mysql_close($this->databaseLink);
$this->debugLine .= '<hr />Closeing Object:<br />';
}
public function getDebugInfo() {
echo "<p>".$this->debugLine."</p>";
if($this->errorString) {
echo '<p style="color: red;">'.$this->errorString.'</p>';
}
$this->debugLine = '';
$this->errorString = '';
}

//run queries
public function runQuery($queryType = "", $sqlString,
$overideToMaster = 0) {
//determine query type if not set
if(!($this->databaseLink = $this->createConnection($sqlString,
$overideToMaster))) {
return false;
}
//retrieve results
$this->debugLine .= ', running: <i style="font-size: 0.8em;">'.
$sqlString.'</i>';
if(!($result = mysql_query($sqlString, $this->databaseLink))) {
$this->errorString = ", error in SQL statement: ".mysql_error().'';
return false;
}
switch($queryType) {
case "value":
$data = $this->getFirstCell($result); break;
case "rows":
$data = $this->getRows($result); break;
case "oneRow":
$data = $this->getOneRow($result); break;
case "insert":
$data = $this->getUpdateQuery($result); break;
default:
$data = $result;
}
//mysql_free_result($result);
return $data;
}
private function getUpdateQuery($result) {
// runs any update query and returns the newly inserted row ID
(autonumber) for an insert
if(mysql_insert_id()) {
return mysql_insert_id();
}
elseif(mysql_affected_rows($this->databaseLink)){
return mysql_affected_rows($this->databaseLink);
}
else {
$this->errorString .= "<br />Maybe no data was affected";
return true;
}
}

private function getFirstCell($result) {
// gets the first cell of the first row (useful for SELECT COUNT(*)
FROM MYTABLE WHERE ID = 123)
if (mysql_num_rows($result) != 1) {
$this->debugLine .= ", the getFirstCell function could not be
executed because it did not have one line";
return false;
}
return mysql_result($result, 0,0);
}

private function getRows($result) {
//returns a multidimensional array
$manyRowArray = array();
while($row = mysql_fetch_assoc($result)) {
$manyRowArray[] = $row;
}
return $manyRowArray;
}

private function getOneRow($result) {
$row = array();
$row = mysql_fetch_assoc($result);
return $row;
}
//database connection
private function createConnection($sqlString, $overideToMaster = 0,
$lastTry = "", $counter = 0) {
//works on the assumption that the SLAVE will be used,
// but only if it passes all the tests
//ratios can be adjusted wtih the oddEvenRatio
$connection = false;
$this->selectedDatabase = "MASTER";
$this->debugLine .= " --- DB connection: ";
if($counter self::maxTries) {
$this->errorString = "Can not connect to database.";
return 0;
}
elseif($overideToMaster) {
//do nothing
$this->debugLine .= ', M: overideToMaster = '.$overideToMaster;
}
elseif($lastTry == "SLAVE") {
//do nothing
$this->debugLine .= ', M: tried Slave last';
}
elseif($this->isTimeCriticalQuery($sqlString)) {
//do nothing
$this->debugLine .= ', M: time critical table present';
}
elseif(!$this->sqlFirstWordIsSafe($sqlString)) {
//do nothing
$this->debugLine .= ', M: first word is not save';
}
elseif($this->isMasterDigit() && overideToMaster !== false) {
//do nothing
$this->debugLine .= ', M: masterDigit';
}
else {
$this->selectedDatabase = "SLAVE";
}
$dbDetails = $this->databaseArray[$this->selectedDatabase];
$this->debugLine .= ', attempt connection to: '.$this-
>selectedDatabase;
if ( $this->databaseLink = mysql_connect($dbDetails["serverName"],
$dbDetails["username"], $dbDetails["password"], $counter) ) {
if(mysql_select_db($dbDetails["databaseName"], $this-
>databaseLink)) {
return $this->databaseLink;
}
else {
$this->errorString .= ', could not select database';
}
}
else {
$this->errorString .= ', could not create database link';
}
//creates a new link if the first one could not be established! JUST
IN CASE (counter 0)
$counter++; //count the amount of connection attempts
$this->debugLine .= ', trying for '.$counter.'<sup>th</suptime to
connect to database';
$lastTry = $this->selectedDatabase;
return $this->createConnection($sqlString, $overideToMaster,
$lastTry, $counter);
}

private function sqlFirstWordIsSafe($sqlString) {
// selects the first word of the query. (e.g. SELECT, INSERT,
etc...) and compares it to a list of exclusions
// needs to be checked if this will work OK in real life by looking
at all the options
$this->firstWord = strtoupper(substr(trim($sqlString), 0,
strpos(trim($sqlString), " ")));
return in_array($this->firstWord, $this->sqlFirstWordIsSafeArray);
}

private function isMasterDigit() {
// here you can work out some ratio for sending queries to Master or
Slave.
// This is the way to adjust the load between the servers
return in_array(intval(substr(time(),-1))+0, $this-
>masterDigitsArray);
}

private function isTimeCriticalQuery($sqlString) {
// Any queries that contain a reference to the any of the
timeCriticalTablesArray will always be send to the master
foreach($this->timeCriticalTablesArray as $value) {
if (stripos($sqlString, $value)!== false) {
return 1;
}
}
return 0;
}

}

Aug 20 '07 #1
0 1352

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: lawrence | last post by:
I had some code that worked fine for several weeks, and then yesterday it stopped working. I'm not sure what I did. Nor can I make out why it isn't working. I'm running a query that should return 3...
5
by: lawrence | last post by:
I posted before, but have now narrowed my problem down to this method. At the start of the method, I test to make sure that I have a resource, a pointer to data returned from a database. This test...
1
by: Johan | last post by:
Hi, The problem is : You have a class A with one or more data variables. You want to store the data variables in a database for example MySQL. Also you do not want to have SQL code in your...
2
by: Bryan | last post by:
Hello, I'm just starting to develop in asp.net and i have a question about using a database connection globally in my app. I have set up the procedures for getting all my connection string info...
14
by: Nick Gilbert | last post by:
Hi, I have an asp.net application which runs from a CD-ROM using Cassini. As such, it is single user only. The application connects to an Access database when it is loaded, and keeps the same...
35
by: Terry Jolly | last post by:
Web Solution Goal: Have a global database connection Why: (There will be 30+ tables, represented by 30+ classes) I only want to reference the database connection once. I put the connection...
3
by: josh.kuo | last post by:
Sorry about the subject, I can't think of a better one. I recently wrote some PHP classes that I think might be of interest to this group. Since I have been reaping the benefits of reading news...
5
by: Slant | last post by:
Here's a question that most will have different answers to. I'm just dying to find a solution that seems halfway automated!! There really are two seperate issues which might be answered by the...
1
tolkienarda
by: tolkienarda | last post by:
i need to update a database table using variables in unusual places here are the update statements mysql_query("UPDATE 'grades' SET '$class' = '$grade' WHERE student='$student'");...
22
by: amygdala | last post by:
Hi, I'm trying to grasp OOP to build an interface using class objects that lets me access database tables easily. You have probably seen this before, or maybe even built it yourself at some...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.