MySQL Class for PHP

article_php

This should get you started if you’re looking to connect to MySQL database.

Requires a simple configuration file where you keep all your variables (user/password/etc, like SITEDB_HOSTNAME).

To connect, just drop these lines in the code

require('mysqlClass.php');
$db = new mysqlClass();
$mystuff = $db->getStuff();

mysqlClass source:

class mysqlClass {
	public $_Link;

	// Construct: Open SQL
	public function __construct()
	{
		$this->_Link = mysql_connect(SITEDB_HOSTNAME, SITEDB_USERNAME, SITEDB_PASSWORD);
		mysql_query("SET NAMES 'utf8'");
		$db = mysql_select_db(SITEDB_DATABASE);
		if(!$this->_Link) $this->callError("Server connection error: " . SITEDB_HOSTNAME . ".");
		if(!$db) $this->callError("Database open error: " . SITEDB_DATABASE . ".");
	}

	// Destruct: Close SQL
	public function __destruct() {
		mysql_close($this->_Link);
	}

        // Update sample
	public function updateStuff($stuff, $id){
		$sql = sprintf("
			UPDATE 		stuff
			SET		stuff = '%s'
			WHERE		id = %d
		",
			mysql_real_escape_string($stuff), mysql_real_escape_string($id)
		);
		$result = mysql_query($sql, $this->_Link);
		if(!$result) $this->callError("Update Error: " . $sql);
	}

        //Insert Sample
	public function insertStuff($stuff){
		$sql = sprintf("
			INSERT INTO		stuff
						(stuff)
				VALUES		('%s');
		",
			mysql_real_escape_string($stuff)
		);
		mysql_query($sql) or $this->callError("Insert Error");
		return mysql_insert_id();
	}

	// Select Sample
	public function getStuff(){
		$sql = sprintf("
                    SELECT          *
                    FROM            stuff
		");
		$result = mysql_query($sql, $this->_Link);
		if(!$result) $this->callError("Result error: " . $sql);
		$queryresult = array();
		while ($row = mysql_fetch_object($result)) {
			$queryresult[] = $row;
		}
		mysql_free_result($result);
		return $queryresult;
	}

        // Show SQL errors
	function callError($details='') {
		echo 'Database Error: ' . $details . ' Error: ' . mysql_error();
	}
}

1 Comment

  1. this helped me out alot! was stuck on this for a while.

Leave a Comment

Back to Top