class for DB ( MYSQL )

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
Odai_GH
Forum Newbie
Posts: 8
Joined: Sun Aug 14, 2011 1:28 pm

class for DB ( MYSQL )

Post by Odai_GH »

hello
i've done a class for Database ( mysql ) beta 1
i'll develop it
here is the class:

Code: Select all

<?php
/**
 * MySQL Class 0.1
 *
 * @author        Odai
 * @copyright        2011
 * @license        GNU General Public License 3 (http://www.gnu.org/licenses/)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details:
 * http://www.gnu.org/licenses/
 *
 */
 class DB{
    /**
    * $DB is an array of 3 @params
    */
    public function  __construct($connection) {
        $this->connect = mysql_connect($connection['host'], $connection['user'], $connection['pass']);
        /**
        * if there's an error on the connection
        */
        if (mysql_error()==true) {
            /**
            * show the error
            */
            die("<h1>error in data:</h1> \n". mysql_error());
            exit;
        }
        else{
            return $this->connect;
        }
    }
    /**
    * function for select the database
    */
    public function select_db($datatbase){
        $this->select=mysql_select_db($datatbase);
        /**
        * if the database is unknown 
        */
        if (mysql_error()==true) {
            /**
            * show the error
            */
            die("<h1>error in data:</h1> \n". mysql_error());
            exit;
        }
        else{
            return $this->select;
        }
    }
    /**
    * function for select the table
    */
    public function select_table($table,$field){
        $this->query=mysql_query("SELECT ".$field." FROM ".$table); 
        /**
        * if there's an error 
        */   
        if (mysql_error()==true) {
            /**
            * show the error
            */
            die("<h1>error in data:</h1> \n". mysql_error());
            exit;
        }
        else{
            return $this->query;
        }
    }
    /**
    * function for extract the value
    */
    public function extract(){
        while($Row = mysql_fetch_object($this->query)){
            return $Row;
        }
    }
    /**
    * function for update colmun
    */
    public function update($table,$field,$value,$wherc,$c){
        $this->updae = mysql_query("UPDATE ".$table." SET $field = $value WHERE $wherc = $c");                     
        /**
        * if there's an error 
        */   
        if (mysql_error()==true) {
            /**
            * show the error
            */
            die("<h1>error in data:</h1> \n". mysql_error());
            exit;
        }
        else{
            return $this->update;
        }
    }
    /**
    * function for delete
    */
    public function delete($table,$wherc,$c){
        $this->delete=mysql_query("DELETE FROM ".$table." WHERE $wherc = $c"); 
                                 
        /**
        * if there's an error 
        */   
        if (mysql_error()==true) {
            /**
            * show the error
            */
            die("<h1>error in data:</h1> \n". mysql_error());
            exit;
        }
        else{
            return $this->delete;
        }
        }
    function __destruct(){
        mysql_close();
    }
}
/**
* End Of tha class
*/ 
?>
uses

Code: Select all

<?
/**
* @uses
$config = array();
$config['host']="localhost"; 
$config['user']="root"; 
$config['pass']="root"; 
$n=new DB($config);
$n->select_db("Notepad");
$n->select_table("daftar","*");
echo $n->extract()->name;
$n->update("example","colmun","new value","wherecolmun","old value");
$n->delete("example","colmun","value");
*/ 
?>
sorry if i put this topic in the wrong forum :S
bye
oscardog
Forum Contributor
Posts: 245
Joined: Thu Oct 23, 2008 4:43 pm

Re: class for DB ( MYSQL )

Post by oscardog »

Well it's a bit underwhelming. And it is in the wrong section, I think.

For a start you have only accounted for updating one field at a time in your update method, you should allow an assoc. array be passed and loop through the array (if it is an array) so the method can actually be used in a real scenario.

Secondly your select has no WHERE clause, you're definitely going to need one of those. Plus you're using mysql_fetch_object which, I believe, is slower than mysql_fetch_array (or even mysql_fetch_row if you know you're only going to have one row to deal with). Typically you don't need to return an object, normally an assoc. array will suffice. As an option, you may want another parameter in your method to return either a single row (mysql_fetch_row), an assoc. array (mysql_fetch_array) or an object (mysql_fetch_object) and then default it to mysql_fetch_array.

I don't know if you've tested it, but I would turn error reporting on... but as far as I am aware, you're meant to declare class variables at the top of your script (just after instantiating the class) so when you use '$this->connect' you should have connect defined at the top of the class like this:

Code: Select all

class example {

var $connect;

public function exampleMethod() {
$this->connect = 'Hello';
}

}
I don't know if you have to define all of the class variables before you use them, I am going to guess you don't, but it's good practise to pre-define your class variables... And when you use a class variable in your update method you've misspelt update and put '$this->updae'.

You should also try to be more consistent with your formatting. Half of the time you indent/tab your code, sometimes you don't. For example look at the destruct & delete methods, the closing curly brace is tabbed in one and not the other. The same goes for single lines of code, sometimes you put spaces before operators and others you don't. Again, this is not going to affect anything but it's good to keep your code consistent but I am a bit of a neat freak when it comes to formatting.
Odai_GH
Forum Newbie
Posts: 8
Joined: Sun Aug 14, 2011 1:28 pm

Re: class for DB ( MYSQL )

Post by Odai_GH »

hello
thanks for visiting my topic
and i'm so glad to reply on my class
and i'll take ur advice
i've another class
thanks a lot :)
oscardog
Forum Contributor
Posts: 245
Joined: Thu Oct 23, 2008 4:43 pm

Re: class for DB ( MYSQL )

Post by oscardog »

No problem, feel free to post an updated version and I'll critique again if you wish (and if I see it).
Odai_GH
Forum Newbie
Posts: 8
Joined: Sun Aug 14, 2011 1:28 pm

Re: class for DB ( MYSQL )

Post by Odai_GH »

oscardog wrote:No problem, feel free to post an updated version and I'll critique again if you wish (and if I see it).
i'll develop it
and i'll make it better :)
and thanks a lot for ur advices
and i've put my 2nd topic hehe :P
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: class for DB ( MYSQL )

Post by Christopher »

Moved to Code Critique.
(#10850)
User avatar
getmizanur
Forum Commoner
Posts: 71
Joined: Sun Sep 06, 2009 12:28 pm

Re: class for DB ( MYSQL )

Post by getmizanur »

first of all, either use php pdo or mysqli instead of mysql extension. mysqli supports ssl connection if you need it for pci compliance or pdo because it make reading sql statement pleasing to the eye. also your functions need to be declared static so that you are able access them without instantiating the class all time. here is how i would do it.

Code: Select all

class DBHandler {
 private static $connHandler;

 private function __construct() {}
 
 public static function getHandler() {
  if(!isset(self::$connHandler)) {
   try{
    self::$connHandler = new PDO(dsn, username, password, array(PDO::ATTR_PRESTENT => DB_PERSISTENCY);
    self::$connHander->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   }catch(PDOException $ex) {
    self::close();
    trigger_error($ex->getMessage(), E_USER_ERROR);
   }
   return self::$connHandler;
  }
 }

 public static function close() {
  self::$connHandler = null;
 }

 public static function execute($sqlQuery, $params = null) {
  try {
   $database_handler = self::getHandler();

   $statement_handler = $database_handler->prepare($sqlQuery);
   $statement_handler->execute($params);
  }catch(PDOException $e) {
   self::close();
   trigger_error($ex->getMessage(), E_USER_ERROR);
  }
 }

 public static function getAll($sqlQuery, $params = null, $fetchStyle= PDO::FETCH_ASSOC) {
  try {
   $database_handler = self::getHandler();

   $statement_handler = $database_handler->prepare($sqlQuery);
   $statement_handler->execute($params);

   $result = $statement_handler->fetchAll($fetchStyle);
  }catch(PDOException $e) {
   self::close();
   trigger_error($ex->getMessage(), E_USER_ERROR);
  }

  return $result;
 }

 public static function getRow($sqlQuery, $params = null, $fetchStyle= PDO::FETCH_ASSOC) {
  try {
   $database_handler = self::getHandler();

   $statement_handler = $database_handler->prepare($sqlQuery);
   $statement_handler->execute($params);

   $result = $statement_handler->fetch($fetchStyle);
  }catch(PDOException $e) {
   self::close();
   trigger_error($ex->getMessage(), E_USER_ERROR);
  }

  return $result;
 }

 public static function getOne($sqlQuery, $params = null) {
  try {
   $database_handler = self::getHandler();

   $statement_handler = $database_handler->prepare($sqlQuery);
   $statement_handler->execute($params);

   $result = $statement_handler->fetch(PDO::FETCH_NUM);
   $result = $result[0];
  }catch(PDOException $e) {
   self::close();
   trigger_error($ex->getMessage(), E_USER_ERROR);
  }

  return $result;
 }
}
ps: this code has not been tested.
Post Reply