<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JJ Is Me &#187; database</title>
	<atom:link href="http://jjis.me/a/tag/database/feed" rel="self" type="application/rss+xml" />
	<link>http://jjis.me</link>
	<description>Me And My Code</description>
	<lastBuildDate>Sun, 29 Jan 2012 22:14:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Database PHP Class</title>
		<link>http://jjis.me/a/253</link>
		<comments>http://jjis.me/a/253#comments</comments>
		<pubDate>Tue, 15 Jun 2010 17:38:25 +0000</pubDate>
		<dc:creator>jj_jiles</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://jjis.me/?p=253</guid>
		<description><![CDATA[I&#8217;m back with another chunk of code. This time, it&#8217;s my database class. I got sick of coming across classes that didn&#8217;t have everything I needed, or didn&#8217;t do it correctly. One of my biggest problems was an inability to nest query calls within another query result&#8217;s output. Example: With this class, that is not [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m back with another chunk of code.  This time, it&#8217;s my database class.</p>
<p>I got sick of coming across classes that didn&#8217;t have everything I needed, or didn&#8217;t do it correctly.  One of my biggest problems was an inability to nest query calls within another query result&#8217;s output.</p>
<p><span id="more-253"></span></p>
<h2>Example:</h2>
<pre class="brush: php; title: ; wrap-lines: false; notranslate">
&lt;?php

// main query
// gets a list of companies from the companies table
$a = &quot;SELECT id, company_name FROM companies&quot;;
$a = $db-&gt;query($a);

while  ($aa = $db-&gt;fetch_object($a) ) :

     echo '&lt;div class=&quot;company_name&quot;&gt;' . $aa-&gt;company_name . '&lt;/div&gt;';

     // get the contacts for each company
     $b = &quot;SELECT contact_name, phone1 FROM contacts WHERE company_id = $aa-&gt;id&quot;; // because we've already used $a, we can't use it again during $a's output
     $b = $db-&gt;query($b);

     // output all contacts for the each company
     while ( $bb = $db-&gt;fetch_object($b) ) : // the same thing as $a, we can not use $aa again during its output
          echo '&lt;div class=&quot;contact_name&quot;&gt;' . $bb-&gt;contact_name . '&lt;/div&gt;';
          echo '&lt;div class=&quot;contact_phone&quot;&gt;' . $bb-&gt;phone1 . '&lt;/div&gt;';
     endwhile;

endwhile;

?&gt;
</pre>
<p>With this class, that is not a problem. The only requirement is that you can&#8217;t name your $sql and $results ($row) variables the same (noted in the code above). Other than that, there&#8217;s nothing to it. It&#8217;s just a way to provide clean, and efficient database interaction.</p>
<h2>Database.Core.php Code</h2>
<ul>
<li>
<p><strong>Updated 06-23-2010: </strong></p>
<ul>
<li>Renamed main database class file to Database.Core.php</li>
<li>Removed the $connection settings and placed them in the Database.Connect.Config.php file. Helps keep hands out of the core file.</li>
<li><strong>show_mysql_error(): </strong>edited so it only receives and passes the original SQL statement, to the error_backtrace() method, upon error.</li>
<li><strong>query(): </strong> no longer fires the die() function and close_db() method. Send the erroring SQL statement to show_mysql_error() method for handling of error output.</li>
<li><strong>multi_query(): </strong> no longer fires the die() function and close_db() method. Send the erroring SQL statement to show_mysql_error() method for handling of error output.</li>
<li><strong>error_backtrace(): </strong>replaced previous method with cleaner code. The error now has formattting for easier readability.</li>
</ul>
</li>
</ul>
<pre class="brush: php; title: ; wrap-lines: false; notranslate">

&lt;?php
/* **********************************************************************
*
* 	DB connection variables
*	Must be set in order to establish a connection to the database
*
********************************************************************** */

$connection = (object) array();
require ( 'Database.Connect.Config.php' );

/* **********************************************************************
* END :::
********************************************************************** */

/* **********************************************************************
*	DatabaseFunctions is a class created to manage database functions
*
*	The class manages all database interraction for purpose of allowing certain things to be
*	turned on and off.  An example would be Error Reporting.  Once the application is on the live
*	server, we can set $config-&gt;ShowErrors to false and error reporting for database erros will no
*	be shown.
*
*	This is real simply to use
*
*	Examples:
*
**********
*
*		Get number of rows returned in a query (you can also nest this:
*			$sql = &quot;SELECT fieldA, fieldB FROM tableA&quot;; // would return 4 rows
*			$sql = $db-&gt;fetch_object($sql);
*			$rows = $db-&gt;num_rows();
*			echo $rows; // 4
*
*		Nested num_rows();
*			$a = &quot;SELECT fieldA FROM tableA&quot;; // would return 2 rows
*			$a = $db-&gt;fetch_object($a);
*			$a_rows = $db-&gt;num_rows();
*			echo $a_rows; // 2
*
*			while ($aa = $db-&gt;fetch_object($a) ) :
*				$b = &quot;SELECT fieldA FROM tableA&quot;; // would return 6 rows
*				$b = $db-&gt;fetch_object($b);
*				$b_rows = $db-&gt;num_rows();
*					echo $b_rows; // 6
*			endwhile;
*
*
**********
*
*
*		Results as Object:
*			$sql = &quot;SELECT fieldA, fieldB FROM tableA&quot;;
*			$sql = $db-&gt;fetch_object($sql);
*
*			while ($row = $db-&gt;fetch_object($sql) ) :
*				echo $row-&gt;fieldA . ': ' . $row-&gt;fieldB;
*			endwhile;
*
*
**********
*
*
*		Results as Array:
*			$sql = &quot;SELECT fieldA, fieldB FROM tableA&quot;;
*			$sql = $db-&gt;fetch_object($sql);
*
*			while ($row = $db-&gt;fetch_array($sql) ) :
*				echo $row['fieldA'] . ': ' . $row['fieldB'];
*			endwhile;
*
*
**********
*
*
*		Return value of a row or field in a row ( uses the rather inefficient mysql_fetch_row() )
*			$sql = &quot;SELECT fieldA, fieldB FROM tableA&quot;;
*			$val = $db-&gt;fetch_row(1);        // would return fieldB's value
*				-- OR --
*			$val = $db-&gt;fetch_row('fieldA'); // would obviously return fieldA's value
*
*
**********
*
*
*		Return value of a query more efficiently (avoids the inefficient mysql_fetch_row() function)
*			$sql = &quot;SELECT fieldA FROM tableA&quot;;
*			$fieldA = $db-&gt;fetch_value($sql); // would return fieldA's value
*
*
**********
*
*
*		 Return the query result set as an array:
*			$sql = &quot;SELECT fieldA, fieldB FROM tableA&quot;; // returns 4 rows
*			$results = $db-&gt;to_array($sql);
*
*			$results[0]['fieldA'] = 'valueA 1';
*			$results[0]['fieldB'] = 'valueB 1';
*
*			$results[1]['fieldA'] = 'valueA 2';
*			$results[1]['fieldB'] = 'valueB 2';
*
*			$results[2]['fieldA'] = 'valueA 3';
*			$results[2]['fieldB'] = 'valueB 3';
*
*			$results[3]['fieldA'] = 'valueA 4';
*			$results[3]['fieldB'] = 'valueB 4';
*
*
********************************************************************** */

class System_Database {

	# set whether errors should be displayed or not
	# probably want to turn off once site is live
	var $displayErrors = false;

	/* ****************************************************************
	*
	* Establish connection to the database
	* Be sure to set the connection info above
	*
	**************************************************************** */
	function connect() {
		global $connection;
		$connection-&gt;mysqlLink = mysql_connect($connection-&gt;host, $connection-&gt;user, $connection-&gt;password);

		# The connection failed for some reason
		if ( !isset($connection-&gt;mysqlLink) ) :
			die(&quot;Error connecting to the server&quot;);

		# The connection is good so lets get the Application Config Settings
		# and create the $config object
		elseif ( isset($connection-&gt;mysqlLink) ) :
			$db_selected = mysql_select_db($connection-&gt;db);

		endif;
	}
	/* ****************************************************************
	* end :::
	**************************************************************** */

	/* ****************************************************************
	*
	* Run the query
	*
	**************************************************************** */
	function sqlId() {
		$id = rand();
		$uniqueId[] = 'sql' . $id;
		$uniqueId[] = 'row' . $id;
		return $uniqueId;
	}
	/* ****************************************************************
	* end :::
	**************************************************************** */

	/* ****************************************************************
	*
	* If $showErrors is set to true or $config-&gt;ShowErrors
	* is set and is true display the error that has occurred
	*
	**************************************************************** */
	function show_mysql_error( $sql ) {
		$this-&gt;error_backtrace( $sql );
		die();
	}
	/* ****************************************************************
	* end :::
	**************************************************************** */

	/* ****************************************************************
	*
	* Run the query
	*
	**************************************************************** */
	function query( $sql ) {
		$this-&gt;result=mysql_query( $sql );
		if ( !$this-&gt;result ) :

			$this-&gt;show_mysql_error( $sql );

		else :

			return $this-&gt;result;

		endif;
	}
	/* ****************************************************************
	* end :::
	**************************************************************** */

	/* ****************************************************************
	*
	* Connect to the server using the mysqli extension
	* This is used automatically during multi_query()
	*
	**************************************************************** */
	function mySqliConnect() {
		global $connection;
		$connection-&gt;mySqli = new mysqli($connection-&gt;host, $connection-&gt;user,  $connection-&gt;password, $connection-&gt;db);
		return $connection-&gt;mySqli;
	}
	/* ****************************************************************
	* end :::
	**************************************************************** */

	/* ****************************************************************
	*
	* Close the mysqli connection once we have finished
	* using the multi_query() method
	*
	**************************************************************** */
	function mySqliClose() {
		global $connection;
		mysqli_close($connection-&gt;mySqli);
	}
	/* ****************************************************************
	* end :::
	**************************************************************** */

	/* ****************************************************************
	*
	* Execture the multi-query
	*
	**************************************************************** */
	function multi_query( $sql ) {

		$mysqli = $this-&gt;mySqliConnect();

		$this-&gt;result=mysqli_multi_query( $mysqli, $sql );

		if ( !$this-&gt;result ) :
			$this-&gt;show_mysql_error( $sql );
		else :
			$this-&gt;mySqliClose();
			return $this-&gt;result;
		endif;
	}
	/* ****************************************************************
	* end :::
	**************************************************************** */

	/* ****************************************************************
	*
	* Returns the results of the query as an object
	*
	* Example:
	*	$sql = &quot;SELECT fieldA, fieldB FROM tableA&quot;;
	*	$sql = $db-&gt;fetch_object($sql);
	*
	*	while ($row = $db-&gt;fetch_object($sql) ) :
	*		echo $row-&gt;fieldA . ': ' . $row-&gt;fieldB;
	*	endwhile;
	*
	**************************************************************** */
	function fetch_object( $sql ) {
		$uniqueIdentifier=rand();
		$$uniqueIdentifier=mysql_fetch_object( $sql );
		return $$uniqueIdentifier;
		unset( $$uniqueIdentifier );
	}
	/* ****************************************************************
	* end :::
	**************************************************************** */

	/* ****************************************************************
	*
	* Returns the results of the query as an array
	*
	* Example:
	*	$sql = &quot;SELECT fieldA, fieldB FROM tableA&quot;;
	*	$sql = $db-&gt;fetch_object($sql);
	*
	*	while ($row = $db-&gt;fetch_object($sql) ) :
	*		echo $row['fieldA'] . ': ' . $row['fieldB'];
	*	endwhile;
	*
	**************************************************************** */
	function fetch_array( $sql ) {
		$uniqueIdentifier=rand();
		$$uniqueIdentifier=mysql_fetch_array( $sql );
		return $$uniqueIdentifier;
		unset( $$uniqueIdentifier );
	}
	/* ****************************************************************
	* end :::
	**************************************************************** */

	/* ****************************************************************
	*
	* Returns the number of rows returned in a query
	*
	**************************************************************** */
	function num_rows($result='') {
		$uniqueIdentifier=rand();
		if (empty($result)) $result = $this-&gt;result;
		$$uniqueIdentifier=mysql_num_rows( $result );
		return $$uniqueIdentifier;
		unset( $$uniqueIdentifier );
	}
	/* ****************************************************************
	* end :::
	**************************************************************** */

	/* ****************************************************************
	*
	* Returns the number of rows affected by a query
	*
	**************************************************************** */
	function rows_affected($result='') {
		$uniqueIdentifier=rand();
		if (empty($result)) $result = $this-&gt;result;
		$$uniqueIdentifier = mysql_rows_affected( $result );
		return $$uniqueIdentifier;
		unset( $$uniqueIdentifier );
	}
	/* ****************************************************************
	* end :::
	**************************************************************** */

	/* ****************************************************************
	*
	* Runs the mysql_result() function, but a little differently
	*
	* if $this-&gt;fetch_row(1), it will return the second field
	* of the first row
	*
	* if $this-&gt;fetch_row('field_name'), it will return the value
	* for 'field_name' in the first row
	*
	**************************************************************** */
	function fetch_row ( $fieldName ) {
		if (is_numeric( $fieldName )) {
			$fieldValue=mysql_result( $this-&gt;result, $fieldName );
		} else {
			$fieldValue=mysql_result( $this-&gt;result, 0, $fieldName );
		}
		return $fieldValue;
	}
	/* ****************************************************************
	* end :::
	**************************************************************** */

	/* ****************************************************************
	*
	* Returns the value of the specified field, in the specified
	* row.
	*
	* If no field or row is specified, it will default to first
	* row, first field
	*
	**************************************************************** */
	function fetch_value ( $sql='', $fieldName='', $row='' ) {
		$i=0;
		$fieldValue = false;

		if (empty($fieldName)) { $fieldName = 0; }
		if (empty($row)) { $row = 0; }
		$ret = array();
		$sql = $this-&gt;query($sql);
		if ($this-&gt;num_rows() &gt; 0) {
			while ($rec = mysql_fetch_array( $sql )) {
				for ($a=0; $a &lt; count($rec); $a++) {
					$ret[$i] = $rec;
				}
				$i++;
			}

			$fieldValue=$ret[$row][$fieldName];
		}

		return ($fieldValue);
	}
	/* ****************************************************************
	* end :::
	**************************************************************** */

	/* ****************************************************************
	*
	* Returns the results of the query as an array
	*
	* Example:
	*	$sql = &quot;SELECT fieldA, fieldB FROM tableA&quot;; // returns 4 rows
	*	$results = $db-&gt;to_array($sql);
	*
	*	$results[0]['fieldA'] = 'valueA 1';
	*	$results[0]['fieldB'] = 'valueB 1';
	*
	*	$results[1]['fieldA'] = 'valueA 2';
	*	$results[1]['fieldB'] = 'valueB 2';
	*
	*	$results[2]['fieldA'] = 'valueA 3';
	*	$results[2]['fieldB'] = 'valueB 3';
	*
	*	$results[3]['fieldA'] = 'valueA 4';
	*	$results[3]['fieldB'] = 'valueB 4';
	*
	**************************************************************** */
	function to_array ( $sql='' ) {
		$i=0;
		$ret = array();
		$sql = $this-&gt;query($sql);
		while ($row = mysql_fetch_assoc( $sql )) {
			for ($a=0; $a &lt; count($row); $a++) {
				$ret[$i] = $row;
			}
			$i++;
		}
		return ($ret);
	}
	/* ****************************************************************
	* end :::
	**************************************************************** */

	/* ****************************************************************
	*
	* closes the database connection
	*
	* PHP nowadays does a really good job of trashing these connection
	* automatically. However, just to be safe, I typically call this
	* method in an include that is loaded after everything else
	*
	**************************************************************** */
	function close_db() {
		global $connection;
		if ($connection-&gt;mysqlLink) :
			mysql_close( $connection-&gt;mysqlLink );
		endif;
	}
	/* ****************************************************************
	* end :::
	**************************************************************** */

	/* ****************************************************************
	*
	* Will format system errors and display them
	*
	**************************************************************** */
	function error_backtrace( $sql ) {

		$errorsThrown = debug_backtrace();
		$errorThrown = $errorsThrown[2];

		echo &quot;
		&lt;style&gt;
			#error-container { width: 100%; color: #333!important; position: relative; background-color: #f3f3f3; border-bottom: 1px dotted #333; }
			#error-wrapper { font: 110%/0.8em arial!important; letter-spacing: 0.02em; width: 850px!important; background-color: #f3f3f3!important; padding: 10px!important; }
			#error-wrapper a { color: #cc6600; }
			#primary-error td { color: #333!important; padding: 4px!important; border: 1px solid #f3f3f3!important; }
			#primary-error td.left {
				width: 120px;
				text-align: right;
				padding: 8px 4px 8px 8px!important;
				margin: 0 8px 1px 0!important;
				background-color: #d3d3d3!important;
			}
			#error-wrapper p { text-align: left; padding: 18px; clear: both!important; }

			#previous-errors th { color: #333!important; padding: 6px; }
			#previous-errors td { color: #333!important; padding: 4px; border-top: 1px solid #666; border-right: 1px solid #666; }
		&lt;/style&gt;
		&quot;;

		echo &quot;&lt;div id=\&quot;error-container\&quot;&gt;&quot;
			. &quot;&lt;div id=\&quot;error-wrapper\&quot;&gt;&quot;
			. &quot;&lt;table id=\&quot;primary-error\&quot;&gt;\n&quot;
			. &quot;&lt;tr&gt;&lt;td class=\&quot;left\&quot;&gt;&lt;strong&gt;Error: &lt;/strong&gt;&lt;/td&gt;&lt;td&gt;Database error&lt;/td&gt;&lt;/tr&gt;\n&quot;
			. &quot;&lt;tr&gt;&lt;td class=\&quot;left\&quot;&gt;&lt;strong&gt;SQL: &lt;/strong&gt;&lt;/td&gt;&lt;td&gt;&quot; . $sql . &quot;&lt;/td&gt;&lt;/tr&gt;\n&quot;
			. &quot;&lt;tr&gt;&lt;td class=\&quot;left\&quot;&gt;&lt;strong&gt;MySQL Error: &lt;/strong&gt;&lt;/td&gt;&lt;td&gt;&quot; . mysql_error() . &quot;&lt;/td&gt;&lt;/tr&gt;\n&quot;
			. &quot;&lt;tr&gt;&lt;td class=\&quot;left\&quot;&gt;&lt;strong&gt;Calling Function: &lt;/strong&gt;&lt;/td&gt;&lt;td&gt;&quot; . $errorThrown['function'] . &quot;&lt;/td&gt;&lt;/tr&gt;\n&quot;
			. &quot;&lt;tr&gt;&lt;td class=\&quot;left\&quot;&gt;&lt;strong&gt;File Name: &lt;/strong&gt;&lt;/td&gt;&lt;td&gt;&quot;.$errorThrown['file'].&quot;&lt;/td&gt;&lt;/tr&gt;\n&quot;
			. &quot;&lt;tr&gt;&lt;td class=\&quot;left\&quot;&gt;&lt;strong&gt;On line: &lt;/strong&gt;&lt;/td&gt;&lt;td&gt;&quot;.$errorThrown['line'].&quot;&lt;/td&gt;&lt;/tr&gt;\n&lt;/table&gt;\n&quot;
			. '&lt;p&gt;&amp;nbsp;&lt;/p&gt;'
			. '&lt;/div&gt;&lt;/div&gt;';
	}
	/* ****************************************************************
	* END :::
	**************************************************************** */

}
/* *********************************************************************************
* END :::
********************************************************************************* */

$db = new System_Database;
?&gt;
</pre>
<h2>Database.Connect.Config.php Code</h2>
<p><em>used for establishing the connection information for your database. this file is automatically included in the Database.Core.php file. just drop it in the same folder and you&#8217;re good to go.</em></p>
<pre class="brush: php; title: ; wrap-lines: false; notranslate">

&lt;?php
	$connection-&gt;host           = 'localhost';
	$connection-&gt;user           = 'user_name';
	$connection-&gt;password    = 'your_password';
	$connection-&gt;db             = 'your_database';
?&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://jjis.me/a/253/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: enhanced
Database Caching 1/16 queries in 0.213 seconds using disk: basic
Object Caching 222/282 objects using disk: basic

Served from: jjis.me @ 2012-02-06 11:28:28 -->
