Return to Snippet

Revision: 51829
at October 5, 2011 09:31 by claudiowebdesign


Initial Code
<?php

	class Database{
		private $host	= '127.0.0.1';
		private $dbname = 'example';
		private $dbpwd  = '';
		private $dbuser = 'root';
		public $link;

		function __construct(){
			$this->link = mysql_connect($this->host,$this->dbuser,$this->dbpwd) or die(mysql_error());
			mysql_select_db($this->dbname,$this->link) or die(mysql_error());
		}
		function __destruct(){
			mysql_close($this->link);
		}
		
		public static function filter($data){
			if(is_array($data))
				$data = array_map('Database::filter', $data);
			else{
				$data = trim(htmlentities(strip_tags($data)));
				if (get_magic_quotes_gpc())
					$data = stripslashes($data);
				$data = mysql_real_escape_string($data);
			}
			return $data;
		}
		
		// $table = string, $conditions = array, $limit = number
		public static function readRecord( $table, $conditions, $limit=false ){
			$query = "SELECT * FROM $table WHERE ";
			foreach($conditions as $a => $b)
				$query .= "$a = '".Database::filter($b)."' AND ";
			$query = substr($query,0,-4).($limit ? ' LIMIT '.Database::filter($limit):'');
			return mysql_fetch_array( mysql_query($query),MYSQL_ASSOC);
		}
		
		// $table = string, $values = array
		public static function addRecord( $table, $values ){
			$q_1 = "INSERT INTO $table(";
			$q_2 = ") VALUES(";
			foreach($values as $field => $val){
				$q_1 .= $field.', ';
				$q_2 .= "'".Database::filter($val)."', ";
			}
			return mysql_query(substr($q_1,0,-2).substr($q_2,0,-2).')');
		}

		// $table = string, $conditions = array, $limit = number
		public static function removeRecord( $table, $conditions, $limit=false ){
			$query = "DELETE FROM $table WHERE ";
			foreach($conditions as $a => $b)
				$query .= "$a = '".Database::filter($b)."' AND ";
			$query = substr($query,0,-4).($limit ? ' LIMIT '.Database::filter($limit):'');
			return mysql_fetch_array( mysql_query($query),MYSQL_ASSOC);
		}
	}

?>

Initial URL
http://claudiobonifazi.com

Initial Description
That's something quick. A basic php class to manage properly a database. Thanks to magic methods opening a database is almost automatic.

Initial Title
Database php class

Initial Tags
database, sql, php

Initial Language
PHP