IT.COM

PHP MySQL database wrapper class

NameSilo
Watch

axilant

Account Closed
Impact
28
PHP:
<?PHP
/*
$hostname = "localhost";
$database = "db";
$username = "root";
$password = "";
$db = new db("$hostname:$database:$username:$password");
*/
class db
{
	var $_version = "1.4";
	var $_lastupdate = "9/20/2005";
	var $_author = "Cody Selzer <[email protected]>";
	function db($args)
	{
		$arg = explode(":", $args);
		$this->host = $arg[0];
		$this->database = $arg[1];
		$this->username = $arg[2];
		$this->password = $arg[3];
		$this->connect();
		$this->select_db();
		$this->close();
	}

	function connect() 
	{
		$this->connect = @mysql_connect("$this->host", "$this->username", "$this->password");
		if(!$this->connect)
		{
			$this->error("Mysql Connection Error","Failed connecting to database server\r\n\r\n" . mysql_error() . "");
		}
		return $this->connect;
	}

	function select_db() 
	{
		$this->select_db = @mysql_select_db($this->database, $this->connect);
		if(!$this->select_db) 
		{
			$this->error("Mysql Connection Error","Failed selecting to database\r\n\r\n" . mysql_error() . "");
		}
		return $this->select_db;
	}
	function query($query) 
	{
		$this->result = mysql_query($query);
		if(!$this->result) 
		{
			$this->error("Mysql Query Error","Error Message: Failed executing database query\r\nDate/Time: " . date('Y-m-d H:i:s') . "\r\nQuery: $query\r\nMySQL Error: " . mysql_error() . "");
		}

		$detect1 = preg_replace('/DELETE/siU', 1, $query);
		$detect2 = preg_replace('/UPDATE/siU', 1, $query);
		$detect3 = preg_replace('/INSERT/siU', 1, $query);

		if($detect1 == 1 || $detect2 == 1 || $detect2 == 1) 
		{
			$this->affected_rows = mysql_affected_rows();
			$this->affected_rows_total += $this->affected_rows;
		}

		$this->counter++;
		return $this->result;
	}

	function fetch_row($query) 
	{
		$this->result = mysql_query($query);
		$this->row = $this->fetch_array($this->result);
		$this->counter++;
		return $this->row;
	}

	function fetch_array($query) 
	{
		$this->row = @mysql_fetch_array($query);
		return $this->row;
	}

	function num_rows($query) 
	{
		$this->result = mysql_query($query);
		$this->num_rows = mysql_num_rows($this->result);
		$this->counter++;
		return $this->num_rows;
	}
	function count_queries() 
	{
		return $this->counter;
	}

	function affected_rows() 
	{
		if($this->affected_rows_total == '0') 
		{
			$this->affected_rows_total = '0';
		}	
		return $this->affected_rows_total; 
	}
	function list_dbs()
	{
		return mysql_list_dbs();
    }
    function tablename($query)
    {
	    return mysql_tablename($query, $this->connect);
    }
    function num_fields($query)
    {
	    return mysql_num_fields($query);
    }
    function error($title,$msg)
    {
	   $page = "<html>\n\<head>\n\t<title>$title</title>\n</head>\n<body>\n\t<p>$msg</p>\n</body>\n</html>";
	   print $page;
    }
    function list_tables()
    {
		$sql = $this->query("SHOW TABLES FROM $this->database");
		while($row = $this->fetch_array($sql))
		{
			$tables[] = $row[0];
		}
		return $tables;
    }

	function close() 
	{
		register_shutdown_function('mysql_close');
	}
	function escape($arr)
	{
		if(is_array($arr))
		{
			foreach($arr as $k => $v)
			{
				if (is_array($v))
				{
					$this->escape($arr[$k]);
				}
				else
				{
					if (function_exists('get_magic_quotes'))
					{
    					if(!get_magic_quotes_gpc())
    					{
        					$arr[$k] = stripslashes($v);
    					}
					}
					if(function_exists('mysql_real_escape_string'))
					{
						$arr[$k] = mysql_real_escape_string($v);
					}
					else
					{
						$arr[$k] = addslashes($v); //real escape function doesnt exist, just readd the slashes.
					}
				}
   			}
		}
		else
		{
			if (function_exists('get_magic_quotes'))
			{
    			if(!get_magic_quotes_gpc())
    			{
        			$arr = stripslashes($arr);
    			}
				}
				if(function_exists('mysql_real_escape_string'))
				{
					$arr = mysql_real_escape_string($v);
				}
				else
				{
						$arr = addslashes($arr);
				}
				return $arr;
		}
	}
	function clean_html($arr)
	{
		if(is_array($arr))
		{
			foreach($arr AS $ar)
			{
				$this->clean_html($ar);
			}
		}
		else
		{
			return(htmlentities($arr));
		}
	}
	function clean($arr = '')
	{
		if(is_array($arr))
		{
			//clean an array that is specified
			$this->clean_html($arr);
			$this->escape($arr);
		}
		else
		{
			$types = array('_POST','_GET','_COOKIE','_SERVER','_SESSION');
			foreach($types AS $type)
			{
				$this->clean_html($$type);
				$this->escape($$type);
			}
		}
	}
	function sql_strip_ticks($data)
	{
		return str_replace("`", "", $data);
	}
	function get_result_fields($query_id="") {
    
   		if ($query_id == "")
   		{
    		$query_id = $this->query_id;
    	}
    
		while ($field = mysql_fetch_field($query_id))
		{
            $Fields[] = $field;
		}		
		return $Fields;
   	}
   	function unescape($arr)
   	{
	   if(is_array($arr))
		{
			foreach($arr as $k => $v)
			{
				if (is_array($v))
				{
					$this->escape($arr[$k]);
				}
				else
				{
        			$arr[$k] = stripslashes($v);
				}
   			}
   			return $arr;
		}
		else
		{		
        	$arr = stripslashes($arr);
			return $arr;
		}
   	}
	//based off of ipb 1.3's code//basicly there code... but a few things changed.
	function get_table_sql($tbl, $create_tbl)
	{		
		if($create_tbl)
		{
			print "DROP TABLE IF EXISTS `$tbl`;";
				$ctable = $this->fetch_row("SHOW CREATE TABLE $tbl");
				print $this->sql_strip_ticks($ctable['Create Table']).";\n";
		}
		$sql = $this->query("SELECT * FROM $tbl");
		$row_count = $this->num_rows("SELECT * FROM $tbl");		
		if ($row_count < 1)
		{
			return true;
		}
		//---------------------------
		// Get col names
		//---------------------------
		
		$f_list = "";
	
		$fields = $this->get_result_fields($sql);
		
		$cnt = count($fields);
		
		for( $i = 0; $i < $cnt; $i++ )
		{
			$f_list .= $fields[$i]->name . ", ";
		}
		
		$f_list = preg_replace( "/, $/", "", $f_list );
		
		while ($row = $this->fetch_array($sql))
		{
			//---------------------------
			// Get col data
			//---------------------------
			
			$d_list = "";
			
			for( $i = 0; $i < $cnt; $i++ )
			{
				if ( ! isset($row[ $fields[$i]->name ]) )
				{
					$d_list .= "NULL,";
				}
				elseif ( $row[ $fields[$i]->name ] != '' )
				{
					$d_list .= "'".$this->escape($row[ $fields[$i]->name ]). "',";
				}
				else
				{
					$d_list .= "'',";
				}
			}
			
			$d_list = preg_replace( "/,$/", "", $d_list );
			
			print("INSERT INTO $tbl ($f_list) VALUES($d_list);\n");
		}
		
		return TRUE;
		
	}
	function doact($step = '',$table)
	{
		switch($step)
		{
			case "0":
			$query = "ANALYZE TABLE $table";
			break;
			case "1":
			$query = "REPAIR TABLE $table";
			break;
			default:
			$query = "OPTIMIZE TABLE $table";
			break;
		}
		return $this->query($query);
	}
	function optimize()
	{
		$tables = $this->list_tables();
		
		foreach($tables AS $table)
		{
			$this->doact("0",$table);
			$this->doact("1",$table);
			$this->doact("",$table);
		}
		
	}
	function backups()
	{
		if (!is_dir("./backups")) {
		    @mkdir("./backups/", "0666");
		}
		$d = dir("./backups");
		$i = $BackupSize = 0;
		$opt = "<select name=\"file\">\n<option>Select one...</option>";
		while (false !== ($entry = $d->read())) 
		{
			if ($entry!="." and $entry!=".." and (ereg(".sql$",$entry)))
			{
				$opt .= "<option>$entry</option>";
			}	
		}
		$opt .= "</select>";
		return $opt;
	}
	function execute_file($file)
	{
		$str = file_get_contents($file);
      	if(!$str)
      	{
         	$this->error("Error opening $file!","Unable to read the contents of $file.");
      	}
      
		$sql = explode(';', $str);
		foreach ($sql as $query) 
		{
			if ($query!="") 
			{
				$r = $this->query($query);
			}
		}
   }
}
?>

Example Usage:

PHP:
$hostname = "localhost";
$database = "db";
$username = "root";
$password = "";
$db = new db("$hostname:$database:$username:$password");
$row = $db->fetch_row("SELECT * FROM tablename");
print_r($row);
Thats only basic usage.

Im planning on making an entire website dedicated to a mysql wrapper in the future.

TODO:
Save Database (backup...)
Fix a few things that i noticed...
Make a complete guide on how to use this.

Updated it, im finishing linkzor.com :P And I got done with database backup/restore. Added unescape() to remove slashes in an array and a non-array.

If anyone finds a bug, please let me know via pm.

Cody Selzer

Rep or np$ (maybe both?) donation would be great :P
 
Last edited:
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
Thanks, I'll test this out in a script I'm currently working on. :)


-Eric
 
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back