Simple Database Class for PHP

simple-database-classWhen creating a PHP Application I always recommend using Object Oriented Programming (OOP) as this makes the working very simple. No long and redundant codes, simple to use, custom methods are some of the delicacies that OOP provides.

I have created a simple PHP class for you all to use in your database driven applications. The class contains methods to connect a database, query a database, fetch the query output in form of both associative and numerically indexed array. have a look..

class db {

var $connection;
var $database;
var $rows = array();
var $count;
var $result;

/* Create a database connection */
function connect ($dbuser,$dbpass,$dbhost,$dbname) {
  $this->connection = mysql_connect($dbhost,$dbuser,$dbpass);
  $this->database = mysql_select_db($dbname);
}

/* Query a MySQL Database */
function query ($query) {
  $this->result = mysql_query($query) or die(mysql_error());
  return $this->result;
}

/* Query a MySQL Dabase
Returns Both arrays Assoc & Indexed */
function getrows ($query) {
  $this->result = mysql_query($query);
  while($r = mysql_fetch_array($this->result,MYSQL_BOTH))
    $this->rows[] = $r;
    mysql_free_result($this->result);
    return $this->rows;
}

/* Count Number of rows query */
function count ($query) {
  $this->result = mysql_query($query);
  $this->count = mysql_num_rows($this->result);
  return $this->count;
}

/* Create a Safe Query */
function escapedata($data) {
    return mysql_real_escape_string($data);
}

/* Close connection */
function __destruct(){ @mysql_close($this->connection); }

}

Related posts:

  1. How to Validate email address with PHP
  2. How to Control A PHP Web Application Remotely
  3. How to Create a WordPress Plugin – Hello World!
  4. How to fake your Feedburner Subscribers
  5. How to remind your visitors to stumble you


The author is a small business owner himself specialising in Web Development. He runs Insight Studios which offers specialized Web Development, SEO Services and PPC Management for Small Business and SME thus ensuring growth and prosperity using the power of social media.

Share This Post

Related Articles

Leave a Reply

© 2012 MyGeekPal. All rights reserved. Site Admin · Entries RSS · Comments RSS
Designed by Insight Studios