D0f517950e189ebe69c903a14cf36fab

I was looking for an easy way to do queries and get their results... This is what I came up with but any refactorings would be greatly appreciated. I'm still a beginner with OO. I pass a keyed array to do prepared queries.

<?php
/**
 * Db Class
 *
 * Database interaction with help from PDO
 *
 * @copyright  2009
 * @version    1.0
 * @author     Alex
 */
 
 class Db
 {
 	private static $_instance = NULL;
 
 
 	private function __construct() {
	
		// can not call me
	}
	
	private function __clone() {
	
		// no!
	}
	
	public static function getInstance() {
	
		if (!self::$_instance)
		{
		
			try {
		
				self::$_instance = new PDO('mysql:host=' . CONFIG_MYSQL_SERVER . ';dbname=' . CONFIG_MYSQL_DATABASE, CONFIG_MYSQL_USERNAME, CONFIG_MYSQL_PASSWORD);;
				self::$_instance-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		
			} catch(PDOException $e) {
			
				trigger_error($e->getMessage());
			
			}
		
		}
		
		return self::$_instance;
		
	
	}
	
	
	
	public static function query($query /*string*/, $bindings = NULL)
	{
	
		$queryPortion = substr($query,0, 6);
	
		try {
	
			if ($bindings) {
	
					$prepared = self::getInstance()->prepare($query);
					
					foreach($bindings as $binding=>$data) { // defaults to string
										
						if (!is_array($data)) {
							$prepared->bindParam($binding, $data); 

						} else {
						
							switch(count($data)) {
							
								case 1:
									$prepared->bindParam($binding, $data['value']);
									break;							
							
								case 2:
									$prepared->bindParam($binding, $data['value'], $data['dataType']);
									break;
									
								case 3:
									$prepared->bindParam($binding, $data['value'], $data['dataType'], (int)$data['length']);
									break;							
								
								default:
									trigger_error('An error has occured with the prepared statement bindings.');
									return false;
									break;
							}
						}
					
					}
					
					$prepared->execute();
							
					return $prepared->fetchAll(PDO::FETCH_ASSOC);
					
	
			} else if (String::match($queryPortion, 'select')) { // if this is a select query
			
				$rows = self::getInstance()->query($query);
			
				return $rows->fetchAll(PDO::FETCH_ASSOC);
					
			} else {
			
				return self::getInstance()->exec($query);

			}
			
			
		} 
		catch(PDOException $e)
		{
			trigger_error($e->getMessage());
		}
		
	
	}
	
	public static function getLastInsertId()
	{
		try {
			self::getInstance()->lastInsertId();
		  }
		catch(PDOException $e)
		{
			trigger_error($e->getMessage());
		}
	
	}
	
	public static function disconnect()
	{
		// kill PDO object
		self::$_instance = NULL;
	
	}
 }

Refactorings

No refactoring yet !

B0de509fc0c0fb426e2caa4903005d35

Gregor

February 25, 2010, February 25, 2010 16:20, permalink

No rating. Login to rate!

Nice job. Here is my very similiar approach with little options on the queries.

<?php
class Database {

      private static $dbh = null;

      private static function connect() {

        try {
            self::$dbh = new PDO('mysql:dbname='.DB_NAME.';host=localhost', USER, PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
            self::$dbh->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            self::$dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);

        } catch (PDOException $e) {
            self::close_db();
            throw new Exception($e->getMessage());
        }
        return self::$dbh;
      }
      public static function close_db() {
          self::$dbh = null;
      }
      public static function prepare($queryString) {
          try {
                $db_handle = self::connect();
                $dbh = $db_handle->prepare($queryString);
                return $dbh;
          } catch(PDOException $e) {
                throw new Exception($e->getMessage());
                self::close_db();
          }
      }
      public static function execute($stmt, $parametri = null) {
          try {
              $stmt->execute($parametri);
          } catch(PDOException $e) {
              throw new Exception($e->getMessage());
              self::close_db();
          }
      }
      public static function getAll($stmt, $parametri = null, $fetch = PDO::FETCH_ASSOC) {
          try {
              self::execute($stmt, $parametri);
              $result = $stmt->fetchAll($fetch);
          } catch(PDOException $e) {
              throw new Exception($e->getMessage());
              self::close_db();
          }
          return $result;
      }
      public static function LastId()
      {
        try {
            self::connect()->lastInsertId();
        }
        catch(PDOException $e)
        {
            throw new Exception($e->getMessage());
        }

      }
      public static function getFirst($stmt,$parametri = null, $fetch = PDO::FETCH_ASSOC) {
          try {
              self::execute($stmt, $parametri);
              $result = $stmt->fetch($fetch);
             
          } catch(PDOException $e) {
              throw new Exception($e->getMessage());
              self::close_db();
          }
          return $result;
      }
}

?>
D41d8cd98f00b204e9800998ecf8427e

Gregor

February 25, 2010, February 25, 2010 16:52, permalink

No rating. Login to rate!

Update

<?php
      public static function LastId()
      {
        try {
            $id = self::$dbh->lastInsertId();
        }
        catch(PDOException $e)
        {
            throw new Exception($e->getMessage());
        }
        
        return $id;

      }
?>

Your refactoring





Format Copy from initial code

or Cancel