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

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

Differences between php4 and php5

These are some of the differences i know between php4 and php5: 1. PHP5 supports more oops concepts like access specifiers and inheritance 2. we can pass objects by reference in php5 (using clone keyword) 3. Exception class included in PHP5 (try and catch) 4. More XML related functions like SimpleXML were included in PHP5 for easy  processing of XML data 5. PHP4 uses Zend engine 1.0 as a parser.PHP5 uses Zend engine 2.0 6. php 5 has improvements in design, security and stablity 7. Magic methods have been included in php5 8. Unified Constructors and Destructors in php5 9. There is a new error level defined as E_STRICT in php5  (notifies deprecated code) 10. Final keyword in php5 indicates that a method cannot be overridden by a  child Note: It is said that PHP5 has Backward compatibility issues with php4.

htaccess disable directory browsing, disable file listing, disable file access

There may be some personal or secure data in a file, that you want to hide from the end user, when it is viewed through a web browser. Ex: http://www.example.com/user_files/24/chat.txt In the above scenario, if the file "chat.txt" contains a secure data, and you dont want to allow end users to directly access the file, or to disable the file listing in the folder "user_files" or "24", use the below code in your .htaccess file inside "user_files" folder: Options -Indexes order allow,deny deny from all