7 Replies - 1777 Views - Last Post: 15 January 2011 - 05:51 AM Rate Topic: -----

#1 KingCuddles  Icon User is offline

  • D.I.C Regular

Reputation: 176
  • View blog
  • Posts: 496
  • Joined: 20-December 08

Database Class Feedback

Posted 14 January 2011 - 07:43 PM

Hey guys,

Could you take a look at my simpleDB class and let me know what you think? what else should I add / remove?


class simpleDB {

  //Connection Variables
  private $db_host;
  private $db_port;
  private $db_user;
  private $db_pass;
  private $db_database;
  private $connection;
  private $query;
  private $connected = false;

  //Error Variables
  private $db_connection_error = "Sorry but something went wrong and I couldn't connect to the server, please try again later.";
  private $db_database_error = "Sorry but something went wrong and I couldn't connect to the database, please try again later.";

  //This is for older PHP 4 which dosnt support the __construct method
  function simpleDB () {
    $this->__construct();
  }

  //When class is created - set up Database variables and try and connect
  public function __construct($host, $port, $user, $pass, $database) {
    //Set the Database Variables
    $this->db_host = $host;
    $this->db_user = $user;
    $this->db_pass = $pass;
    $this->db_database = $database;

    //See if custom port has been specified..
    if (isset($port) && $port != ""){
      $this->db_port = $port;
    }
    //If not set the port to 3306, the default MYSQL port
    else {
      $this->db_port = 3306;
    }

    //Connect to the Database
    $this->connect();
  }

  //Connect to the Database
  private function connect() {
    $this->connection = mysql_connect($this->db_host.":".$this->db_port, $this->db_user, $this->db_pass) or die($this->db_connection_error);

    if($this->connection) {
      $database = mysql_select_db($this->db_database, $this->connection) or die($this->db_database_error);
      $this->connected = true;
    }
  }

  //Query the Database
  function query($query) {
    if (isset($this->connected) && $this->connected == true) {
      $this->query = $query;
      $this->query = mysql_query($this->query) or die();
    }

    return $this->query;
  }

  //Return the Query as an Array - Some people may use it but I much prefer Objects/Accoc
  function fetch_array($array) {
    $this->array = $array;
    $this->array = mysql_fetch_array($this->array);
    $this->queries++;

    return $this->array;
  }

  //Count and return the number of rows returned from a query
  function num_rows($rows) {
    $this->rows = $rows;
    $this->rows = mysql_num_rows($this->rows);

    return $this->rows;
  }

  //Return the Query as an Associative Array
  function fetch_assoc($assoc) {
    $this->assoc = $assoc;
    $this->assoc = mysql_fetch_assoc($this->assoc);
    $this->queries++;

    return $this->assoc;
  }

  //Return the Query as an Object -> the methods become the field names
  function fetch_object($object) {
    $this->object = $object;
    $this->object = mysql_fetch_object($this->object);
    $this->queries++;

    return $this->object;
  }

  //Destroy the connection
  function destroy() {
    if (is_resource($this->query)) {
      mysql_free_result($this->query);
    }
    mysql_close($this->connection);
  }


//end class
}


Is This A Good Question/Topic? 4
  • +

Replies To: Database Class Feedback

#2 aaron1178  Icon User is offline

  • Dovakiin, Dragonborn
  • member icon

Reputation: 169
  • View blog
  • Posts: 1,297
  • Joined: 22-October 08

Re: Database Class Feedback

Posted 14 January 2011 - 07:53 PM

Pretty cool :P I love OOP and i keep rewriting my database class every 2 days :P when i learn a new trick in a object orientated language. Keep up the good work :clap:

PS: You could always add a mysql_pconnect(); connection, to make a persistent connection if one is available.

This post has been edited by aaron1178: 14 January 2011 - 07:55 PM

Was This Post Helpful? 0
  • +
  • -

#3 KingCuddles  Icon User is offline

  • D.I.C Regular

Reputation: 176
  • View blog
  • Posts: 496
  • Joined: 20-December 08

Re: Database Class Feedback

Posted 14 January 2011 - 07:54 PM

Want to share some of yours, I haven't really tested mine yet, but I am assuming I have probably missed almost everything useful.
Was This Post Helpful? 0
  • +
  • -

#4 aaron1178  Icon User is offline

  • Dovakiin, Dragonborn
  • member icon

Reputation: 169
  • View blog
  • Posts: 1,297
  • Joined: 22-October 08

Re: Database Class Feedback

Posted 14 January 2011 - 08:13 PM

here it is:
database.driver.php
<?php
/*
 --MySQL Driver version: 1.0
 If you have a vast knowledge of MySQL
 please edit to optimize the databasing.
 
 !Document is detailed with comments!
*/
//We create a class named mysql
class mysql
{
 //declare some private variable (vars cannot be accessed out side this class)
 private $host;
 private $user;
 private $pass;
 private $db;
 private $errors = 0;
 private $persistent = 0;
 private $id = 0;
 //Our first function configures the variables for future reference
 public function configure($host, $user, $pass, $db, $persistent=0, $errors=0, $id=0)
 {
   $this->host = $host;
   $this->user = $user;
   $this->pass = $pass;
   $this->db   = $db;
   $this->persistent = $persistent;
   $this->errors = $errors;
   $this->id = $id;
 }
 //This function will establish a connection and select the database
 public function connect()
 {
	//A little error check to see if variables have been set
   if(!$this->host){$this->host="localhost";}
   if(!$this->user){$this->user="root";$this->password="";}
   if(!$this->pass){$this->pass="";}
   if(!$this->db){die("Undefined Database!!!");}
   //Try to establish a persistent connection, else try to establish a normal connection
   if($this->persistent == 1)
   {
     $this->id = mysql_pconnect($this->host, $this->user, $this->pass) or die("Could not establish a Persistent Connection, trying to conjnect normally...");   
   }
   else
   {
	 $this->id = mysql_connect($this->host, $this->user, $this->pass) or die("Could not establish a connection. Please check your connection settings!!!");   
   }
   //Connect to database using above connection (either persistent or normal)
   mysql_select_db($this->db, $this->id) or die("Could not find database on host: $this->host");
 }
 //Now we will create the query function that will be use as mysql_query();
 public function query($query_string)
 {
   $this->query_string = $query_string;
   $this->query = mysql_query($this->query_string, $this->id) or die("Cannot execute query!!!".mysql_error());
   return $this->query;
 }
 //Next we will make the function that will fetch the assoc array
 public function fetch_assoc($array)
 {
   $this->array = $array;
   $this->array = mysql_fetch_assoc($this->array);
   return $this->array;	
 }
 //Now the function to num the rows (Count)
 public function num_rows($rows)
 {
   $this->row = $rows;
   $this->row = mysql_num_rows($this->row);
   return $this->row;
 }
 //A simple function to sanitize strings
 public function clean($string)
 {
   $this->string = $string;
   $this->string = mysql_real_escape_string(strip_tags(stripcslashes($this->string)));	
   return $this->string;
 }
 //Function to free some memory
 public function free_memory($memory)
 {
   $this->memory = $memory;
   if(is_resource($this->memory))
   {
     $this->memory = mysql_free_result($this->memory);		
   }
   else
   {
     return;	
   }
   return $this->memory;
 }
 //Close Connection
 public function close()
 {
	$this->connection = $this->id;
	mysql_close($this->connection);
 }

}
?>


It's not the best but it gets the job done :P

This post has been edited by aaron1178: 14 January 2011 - 08:16 PM

Was This Post Helpful? 0
  • +
  • -

#5 Dormilich  Icon User is online

  • 痛覚残留
  • member icon

Reputation: 3480
  • View blog
  • Posts: 10,027
  • Joined: 08-June 10

Re: Database Class Feedback

Posted 15 January 2011 - 03:30 AM

View PostKingCuddles, on 15 January 2011 - 03:43 AM, said:

Could you take a look at my simpleDB class and let me know what you think?

(may not be the most pleasent opinion )

when making a DB class, stop using outdated functions (all of the mysql_* functions are outdated). PHP already has 2 proper and maintained DB handling classes (PDO, MySQLi) which are far more suited for use in OOP.
Was This Post Helpful? 4
  • +
  • -

#6 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 434
  • View blog
  • Posts: 1,042
  • Joined: 08-March 09

Re: Database Class Feedback

Posted 15 January 2011 - 05:24 AM

You could make your classes throw exceptions rather than using die. Although that wouldn't apply to KingCuddles since his class is designed to work with PHP 4. Exceptions can allow you to have more graceful error handling.

the manual

D.I.C tutorial

And I agree with aaron1178 OOP PHP is great :D. I am working at my first real web programming job. We are basically working with hundreds of pages of poorly written procedural code. Languages are mixed together all over the place, it's not uncommon to see CSS/javascript/html/php all on in one place.

Since we started refactoring and introducing OOP along with an MVC design pattern to separate business logic from presentation it has become much easier to work with and develop(not to mention look at).
Was This Post Helpful? 1
  • +
  • -

#7 aaron1178  Icon User is offline

  • Dovakiin, Dragonborn
  • member icon

Reputation: 169
  • View blog
  • Posts: 1,297
  • Joined: 22-October 08

Re: Database Class Feedback

Posted 15 January 2011 - 05:48 AM

View PostDormilich, on 15 January 2011 - 03:30 AM, said:

when making a DB class, stop using outdated functions (all of the mysql_* functions are outdated). PHP already has 2 proper and maintained DB handling classes (PDO, MySQLi) which are far more suited for use in OOP.


I do agree with you Dormilich, but throughout the 5 years I have been using php i have never really gotten around to using mysqli :P

But OOP with php is great. I love it, because it is somewhat like to C# language (in some aspects) but on the other hand it has its moments

Thanks,
Was This Post Helpful? 0
  • +
  • -

#8 D-2010  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 8
  • Joined: 28-January 10

Re: Database Class Feedback

Posted 15 January 2011 - 05:51 AM

I am with Dormilich, PDO is awesome! Here is my DB class for little guestbook app while learning about PDO.

class DBA {
   private static $instance;
   private $dbh;
   var $error = "";
   
   private function __construct(){
      $this->dbh = new PDO('sqlite:guestbook.sdb');
      $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   }
              
   public static function getInstance(){
     if (!isset(self::$instance)) {
         $c = __CLASS__;
         self::$instance = new $c;
     }
   
     return self::$instance;
   }

   private function getEntries(){
      $sql = "select * from entries order by id desc";
      $rs = $this->dbh->query($sql)
                 ->fetchAll(PDO::FETCH_CLASS, 'entry');
      return $rs;      
   }
   
   private function saveEntry(){                  
      $stmt = $this->dbh->prepare("INSERT INTO entries (`email`, `title`, `message`) VALUES (:email, :title, :message)");
                 
      $stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
      $stmt->bindParam(':title', $_POST['title'], PDO::PARAM_STR);
      $stmt->bindParam(':message', $_POST['message'], PDO::PARAM_STR);      
      $stmt->execute();
   }
   
   function __call($method, $params){
      try {
         $this->error = "";
         return $this->$method();         
      } catch (PDOException $e) {
         $this->error = $e->getMessage();
         return false;
      }
   }
   
   function __destruct(){
      $this->dbh = null;
   }
}



All I needed to use it is $this->entries = DBA::getInstance()->getEntries();

This post has been edited by D-2010: 15 January 2011 - 05:53 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1