MySQL wrapper class (PHP)


I'm not saying that this is the best implementation of a MySQL wrapper class for PHP. I'm not advocating its use in production code.

However, this is what I've used in most scripts I've thrown together in the last few years – I hate having to throw a mysql_error call after every query, y'know?

<?php
 
define('CLIENT_LONG_PASSWORD', 1);
 
class MySQLWrapper
{
	var $server_port	=		'localhost:3306';
	var $database 		=		'whatever';
	var $username 		=		'a username';
	var $password 		=		'a password';
	var $force_long_password = false;
	var $db_object;
 
	function __construct($server_port = "", $database = "", $username = "", $password = "", $force_long_password = false)
	{
		$this->server_port = $server_port;
		$this->database = $database;
		$this->username = $username;
		$this->password = $password;
		$this->force_long_password = $force_long_password;
 
		if ($this->server_port != "")
		{
			$this->Connect();
		}
	}
 
	function Connect()
	{
		if (isset($this->db_object))
		{
			if (!mysql_ping($this->db_object))
			{
				unset($this->db_object);
				$this->Connect();
			}
		}
		else
		{
			$db_object = mysql_connect($this->server_port, $this->username, $this->password, false, $this->force_long_password ? CLIENT_LONG_PASSWORD : 0);
			if ($this->database != '' && !mysql_select_db($this->database))
			{
				$result = mysql_error();
				print "Select database failed for $this->database: $result\n";
			}
		}
	}
 
	function Disconnect()
	{
		$return = true;
 
		if (isset($this->db_object))
		{
			$return = mysql_close($this->db_object);
			unset($this->db_object);
		}
 
		return $return;
	}
 
	function Execute($query)
	{
		$this->Connect();
		$result = mysql_query($query);
		if (!$result)
		{
			$result = mysql_error();
			print "Query failed: $result\n";
			print "Teh query itself: $query\n";
		}
		return $result;
	}
}
 
?>

You may find this slightly better than using PHP's MySQL functions straight out of the box. Or not. Who can say?

  1. #1 by Stefan Gabos on 2011-04-19 - 15:15

    Also, you might want to chech out this MySQL wrapper at http://stefangabos.ro/php-libraries/zebra-database/. It's one file only, it's pretty small, does a lot of stuff right and has a very nice debugging console. It may be helpful for further developing your own.

(will not be published)