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...

Joomla validate chrono forms using jquery

It is a common practice to use Chrono forms in our joomla site to setup various forms in the site, be it a contact us form, submit a ticket form, or whatever. I have set the option "validate form" to "No" under chronoform settings in admin panel, and also preferred to not include any js or css files. For validating the chrono forms, i prefer jquery. So first lets add jquery support in our joomla. It is quite simple: 1. Download jquery.js and jquery_min.js (1.4.2 version is enough) and place them in media/system/js folder of your joomla. 2. Edit libraries->joomla->html->html->behavior.php, and add the following function below the mootools() function: function jQuery($debug = null)     {         static $loaded;         global $mainframe;         // Only load once         if ($loaded) {    ...

Mysql join examples

1. Inner join: Sample Fields in "person" table:  id, email, password, firstname, lastname Sample Fields in "personprofile" table: person_id, age, dob, city, country, phone, mobile Query: select * from person inner join `personprofile` on person.id=personprofile.person_id and person.id=9; 2.  Left join: Sample fields in "employee" table: emp_id (primary), name, active Sample fields in "online" table: id (primary), user_id (references emp_id), online Query: SELECT *  FROM employee e left join online o on e.emp_id = o.user_id where e.active=1; Note the use of "where" in the above query, instead of normal "and". It will give the accurate results.