473,890 Members | 1,262 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 $timeCriticalTa blesArray = array("temp2"); // tables that
should always be done on the master
private $databaseArray = array(
"MASTER" =array("serverN ame"=>'xxx', "username"=>'xx x-1',
"password"=>'xx x', "databaseName"= >'xxx-1'),
"SLAVE" =array("serverN ame"=>'xxx', "username"=>'xx x-2',
"password"=>'xx x', "databaseName"= >'xxx-2')
);
private $sqlFirstWordIs SafeArray = array("SELECT") ; //THESE HAVE TO
BE UPPERCASE!!!!!! !!!!!!!
private $masterDigitsAr ray = 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($th is->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($query Type = "", $sqlString,
$overideToMaste r = 0) {
//determine query type if not set
if(!($this->databaseLink = $this->createConnecti on($sqlString,
$overideToMaste r))) {
return false;
}
//retrieve results
$this->debugLine .= ', running: <i style="font-size: 0.8em;">'.
$sqlString.'</i>';
if(!($result = mysql_query($sq lString, $this->databaseLink)) ) {
$this->errorString = ", error in SQL statement: ".mysql_error() .'';
return false;
}
switch($queryTy pe) {
case "value":
$data = $this->getFirstCell($ result); break;
case "rows":
$data = $this->getRows($resul t); break;
case "oneRow":
$data = $this->getOneRow($res ult); break;
case "insert":
$data = $this->getUpdateQuery ($result); break;
default:
$data = $result;
}
//mysql_free_resu lt($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_af fected_rows($th is->databaseLink)) {
return mysql_affected_ rows($this->databaseLink );
}
else {
$this->errorString .= "<br />Maybe no data was affected";
return true;
}
}

private function getFirstCell($r esult) {
// 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($r esult, 0,0);
}

private function getRows($result ) {
//returns a multidimensiona l array
$manyRowArray = array();
while($row = mysql_fetch_ass oc($result)) {
$manyRowArray[] = $row;
}
return $manyRowArray;
}

private function getOneRow($resu lt) {
$row = array();
$row = mysql_fetch_ass oc($result);
return $row;
}
//database connection
private function createConnectio n($sqlString, $overideToMaste r = 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->selectedDataba se = "MASTER";
$this->debugLine .= " --- DB connection: ";
if($counter self::maxTries) {
$this->errorString = "Can not connect to database.";
return 0;
}
elseif($overide ToMaster) {
//do nothing
$this->debugLine .= ', M: overideToMaster = '.$overideToMas ter;
}
elseif($lastTry == "SLAVE") {
//do nothing
$this->debugLine .= ', M: tried Slave last';
}
elseif($this->isTimeCritical Query($sqlStrin g)) {
//do nothing
$this->debugLine .= ', M: time critical table present';
}
elseif(!$this->sqlFirstWordIs Safe($sqlString )) {
//do nothing
$this->debugLine .= ', M: first word is not save';
}
elseif($this->isMasterDigit( ) && overideToMaster !== false) {
//do nothing
$this->debugLine .= ', M: masterDigit';
}
else {
$this->selectedDataba se = "SLAVE";
}
$dbDetails = $this->databaseArra y[$this->selectedDataba se];
$this->debugLine .= ', attempt connection to: '.$this-
>selectedDataba se;
if ( $this->databaseLink = mysql_connect($ dbDetails["serverName "],
$dbDetails["username"], $dbDetails["password"], $counter) ) {
if(mysql_select _db($dbDetails["databaseNa me"], $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.'<su p>th</suptime to
connect to database';
$lastTry = $this->selectedDataba se;
return $this->createConnecti on($sqlString, $overideToMaste r,
$lastTry, $counter);
}

private function sqlFirstWordIsS afe($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(subs tr(trim($sqlStr ing), 0,
strpos(trim($sq lString), " ")));
return in_array($this->firstWord, $this->sqlFirstWordIs SafeArray);
}

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-
>masterDigitsAr ray);
}

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

}

Aug 20 '07 #1
0 1378

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

Similar topics

2
2274
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 items from the database. I then get a count of the return, which correctly tells me that I've got 3 items. I then go into a for loop which I expect to loop 3 times and print out the 3 items. Here is where things get strange: it loops 3 times and...
5
2046
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 is coming back true, so the next line runs, which attempts to get the next row from the dataset. This brings back nothing. On the queries I'm running right now, the first row will be fetched, but then no further rows. If I expect 20 rows back, I...
1
1514
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 class A. Is there a way to translate the Object A to a sql independed structure. I think it is something with persistent objects or am I wrong. has anyone experience with this ?
2
3502
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 which each page will use, but my question relates to how to use the database connection i create in all my classes. I have a database class, in a separate namespace and file, i created that handles all the connection opening, executing statements...
14
4830
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 connection open all the time (as it's single user, this shouldn't be a problem). There is logic in the code to ensure that the connection is
35
4866
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 string in the web.config. I created a class with a static database connection and the class opens and closes the database.
3
2956
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 groups for years, I figure it's time for me to contribute a little bit back, maybe some people out there will find this useful. * Introduction This is a "how-to" style article, showing by example how to dynamically
5
2339
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 same answer. Web App: - constants.php begin - define("DB_HOST", "locahost"); .... to include the standard connection info define("DB_NAME", "mydatabase");
1
2006
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'"); mysql_query("UPDATE 'assignments' SET '$class' = '$grade' WHERE student='$student'"); mysql_query("UPDATE 'comments' SET '$class' = '$grade' WHERE student='$student'"); now i was just showed by ron how to recive post stuff and that is where the variables come...
22
3547
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 point in time. I have studied some examples I found on the internet, and am now trying to build my own from scratch. I have made a default table class (DB_Table), a default validation class (Validator) which is an object inside DB_Table and my...
0
9978
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11228
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10814
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10922
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10462
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9630
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8016
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4676
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3276
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.