Skip to main content

OOPS way of querying database !!!

Tired of writing those connect and execute query statements in php all the time ?
Now you have got an OOPS way of executing your queries...

Using this, there are many advantages like avoiding the reuse of code and improvement in performance.

Supose we have a user table with the fields id, name, branch and city:

CREATE TABLE IF NOT EXISTS `user` (
`id` int(2) NOT NULL auto_increment,
`name` varchar(25) NOT NULL,
`branch` varchar(25) NOT NULL,
`city` varchar(25) NOT NULL,
PRIMARY KEY (`id`)
)

Dump few values into it:

INSERT INTO `user` (`id`, `name`, `branch`, `city`) VALUES
(1, 'ravi', 'CSE', 'Hyderabad'),
(2, 'kiran', 'Mech', 'Vijayawada'),
(3, 'prasad', 'CSIT', 'Vizag'),
(4, 'sashi', 'ECE', 'Tirupati');



Now to perform the task, the following are the steps:

1) First create a config file with the details of the constants like:
host, username, password, database name and all the table names of your database.
Name this file as: config.inc.php

<?php
define('DB_SERVER', "localhost");
define('DB_USER', "root");
define('DB_PASS', "");
define('DB_DATABASE', "smarty"); // a sample database

define('TABLE_USERS', "user"); // better to define even tables
?>

2) now write the class file containing the methods for executing your queries and returning the result sets. Name this file as: Database.class.php

<?php
class Database {

var $server = ""; //database server
var $user = ""; //database login name
var $pass = ""; //database login password
var $database = ""; //database name
var $pre = ""; //table prefix

function Database($server, $user, $pass, $database, $pre=''){
$this->server=$server;
$this->user=$user;
$this->pass=$pass;
$this->database=$database;
$this->pre=$pre;
}

function connect($new_link=false) {
$this->link_id=@mysql_connect($this->server,$this->user,$this->pass,$new_link);

if (!$this->link_id) {//open failed
$this->oops("Could not connect to server: <b>$this->server</b>.");
}

if(!@mysql_select_db($this->database, $this->link_id)) { //no database
$this->oops("Could not open database: <b>$this->database</b>.");
}

// unset the data so it can't be dumped
$this->server='';
$this->user='';
$this->pass='';
$this->database='';
}

function close() {
if(!@mysql_close($this->link_id)){
$this->oops("Connection close failed.");
}
}

function query($sql) {
// do query
$this->query_id = @mysql_query($sql, $this->link_id);

if (!$this->query_id) {
$this->oops("<b>MySQL Query fail:</b> $sql");
return 0;
}

$this->affected_rows = @mysql_affected_rows($this->link_id);

return $this->query_id;
}

function fetch_assoc($query_id=-1) {
// retrieve row
// fetches and returns results one line at a time

if ($query_id!=-1) {
$this->query_id=$query_id;
}

if (isset($this->query_id)) {
$record = @mysql_fetch_assoc($this->query_id);
}else{
$this->oops("Invalid query_id: <b>$this->query_id</b>. Records could not be fetched.");
}

return $record;
}


function oops($msg='') {
if($this->link_id>0){
$this->error=mysql_error($this->link_id);
$this->errno=mysql_errno($this->link_id);
}
else{
$this->error=mysql_error();
$this->errno=mysql_errno();
}
?>
<table align="center" border="1" cellspacing="0" style="background:white;color:black;width:80%;">
<tr><th colspan=2>Database Error</th></tr>
<tr><td align="right" valign="top">Message:</td><td><?php echo $msg; ?></td></tr>
<?php if(strlen($this->error)>0) echo '<tr><td align="right" valign="top" nowrap>MySQL Error:</td><td>'.$this->error.'</td></tr>'; ?>
<tr><td align="right">Date:</td><td><?php echo date("l, F j, Y \a\\t g:i:s A"); ?></td></tr>
<tr><td align="right">Script:</td><td><a href="<?php echo @$_SERVER['REQUEST_URI']; ?>"><?php echo @$_SERVER['REQUEST_URI']; ?></a></td></tr>
<?php if(strlen(@$_SERVER['HTTP_REFERER'])>0) echo '<tr><td align="right">Referer:</td><td><a href="'.@$_SERVER['HTTP_REFERER'].'">'.@$_SERVER['HTTP_REFERER'].'</a></td></tr>'; ?>
</table>
<?php
}

}
?>


3) Finally write your query and execute it: test.php

<?php

require("config.inc.php"); // I'm using a separate config file

require("Database.class.php"); // pull the database class file

$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);

$db->connect(); // connect to the server

// your main code would go here

$sql = "select name,branch,city from ".TABLE_USERS." where id in (1,2,4)";

$res = $db->query($sql);

echo '<table style="border:2px solid #F5CC99" width="400">
<tr style="background-color:#33CCd5"><td>Name</td><td>Branch</td><td>City</td></tr>';

while ($record = $db->fetch_assoc($res)) {
echo "<tr>
<td>$record[name]</td>
<td>$record[branch]</td>
<td>$record[city]</td>
</tr>";
}

echo '</table>';

// and when finished, remember to close connection
$db->close();

?>

Now this will display a table with the 3 rows of users.
Enjoy !

Comments

Popular posts from this blog

Retaining checkbox status of a form after submitting it

we will learn here how to post back or retain the value ( status ) of the checkbox. We will use php header redirection to post back the values to our main page where checkbox is present. We will call form page as first page and action or submitted page as second page. The form data will be received by second page and it is supposed to post back the form data back to form page by using query string through address bar. To keep the second page simple we will keep only the redirection part. Here we have excluded the part which takes care if the form passes its validation and execute the actual script (redirection part). Here is the code of our form with two checkboxes, pb-check.php <?php $t1=$_GET['t1']; $t2=$_GET['t2']; if($t1=="yes"){$t1v="checked";} else{$t1v=="";} if($t2=="yes"){$t2v="checked";} else{$t2v=="";} ?> HTML Form code: <form method="post" action="pb-chk.php"> <inp...

Identify the user's browser

Sometimes there arises a need to identify the user's browser. It is pretty easy to find browser with jquery. So if you have included jquery in your page, it takes a simple line to identify the browser:  if ($. browser . msie ) {} // IE if (($.browser.msie) && ($.browser.version == '6.0')) {} // IE6 if ($. browser . opera ) {} // opera if ($. browser . mozilla) {} // Firefox With the help of php, you can get the browser  details with the help of:  $_SERVER['HTTP_USER_AGENT']; Or you can even use the combined version of php and javascript. php + javascript code: <script type="text/javascript"> var string1 = "<?php echo $_SERVER['HTTP_USER_AGENT']; ?>"; // Browser string var myRegExp1 = /Firefox/; var matchPos1 = string1.search(myRegExp1); var myRegExp2 = /Chrome/; var matchPos2 = string1.search(myRegExp2); var myRegExp3 = /MSIE/; var matchPos3 = string1.search(myRegExp3); if(matchPos1 != -1) ...

Facebook connect using graph api

An example of using facebook graph api to authenticate users: Setup a new application in facebook apps and get the app id and secret. Now follow the steps: Remember to give the same url in the below code, as that of the app settings. <?php if( !isset($_GET['code'])) { ?> <a href="https://graph.facebook.com/oauth/authorize?client_id=xxxxxxxx&redirect_uri=http://xxxxxxxxxxxxxxxx/">Connect using Facebook</a> <?php } $code = trim($_GET['code']); if(isset($_GET['code'])) $token = file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=xxxxxxxx&redirect_uri=http://xxxxxxxxxxxxxxx&client_secret=xxxxxxxxxxxx&code=$code"); $token = explode("=", $token); if(isset($_GET['code'])) $user = json_decode(file_get_contents('https://graph.facebook.com/me?access_token='.$token[1]));  print_r($user); ?>