PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Mon Dec 17, 2018 10:53 am

All times are UTC - 5 hours




Post new topic Reply to topic  [ 7 posts ] 
Author Message
 Post subject: class for DB ( MYSQL )
PostPosted: Sun Aug 14, 2011 1:38 pm 
Offline
Forum Newbie

Joined: Sun Aug 14, 2011 1:28 pm
Posts: 8
hello
i've done a class for Database ( mysql ) beta 1
i'll develop it
here is the class:
Syntax: [ Download ] [ Hide ]
<?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
Syntax: [ Download ] [ Hide ]
<?
/**
* @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


Top
 Profile  
 
PostPosted: Sun Aug 14, 2011 3:04 pm 
Offline
Forum Contributor

Joined: Thu Oct 23, 2008 4:43 pm
Posts: 245
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:

Syntax: [ Download ] [ Hide ]
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.


Top
 Profile  
 
PostPosted: Sun Aug 14, 2011 3:55 pm 
Offline
Forum Newbie

Joined: Sun Aug 14, 2011 1:28 pm
Posts: 8
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 :)


Top
 Profile  
 
PostPosted: Sun Aug 14, 2011 4:00 pm 
Offline
Forum Contributor

Joined: Thu Oct 23, 2008 4:43 pm
Posts: 245
No problem, feel free to post an updated version and I'll critique again if you wish (and if I see it).


Top
 Profile  
 
PostPosted: Sun Aug 14, 2011 4:03 pm 
Offline
Forum Newbie

Joined: Sun Aug 14, 2011 1:28 pm
Posts: 8
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


Top
 Profile  
 
PostPosted: Sun Aug 14, 2011 6:28 pm 
Offline
Site Administrator
User avatar

Joined: Wed Aug 25, 2004 7:54 pm
Posts: 13585
Location: New York, NY, US
Moved to Code Critique.

_________________
(#10850)


Top
 Profile  
 
PostPosted: Sun Sep 04, 2011 2:42 pm 
Offline
Forum Commoner
User avatar

Joined: Sun Sep 06, 2009 12:28 pm
Posts: 71
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.
Syntax: [ Download ] [ Hide ]
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.


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 7 posts ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
Powered by phpBB® Forum Software © phpBB Group