<?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>Justin Carmony &#187; Database</title>
	<atom:link href="http://www.justincarmony.com/blog/tag/database/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.justincarmony.com/blog</link>
	<description>Web Designer &#38; Software Engineer</description>
	<lastBuildDate>Wed, 01 Feb 2012 04:30:16 +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>The Dangers of Twitter!</title>
		<link>http://www.justincarmony.com/blog/2009/01/08/the-dangers-of-twitter/</link>
		<comments>http://www.justincarmony.com/blog/2009/01/08/the-dangers-of-twitter/#comments</comments>
		<pubDate>Thu, 08 Jan 2009 07:00:34 +0000</pubDate>
		<dc:creator>Justin Carmony</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Funny]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Twitter]]></category>
		<category><![CDATA[Web 2.0]]></category>

		<guid isPermaLink="false">http://www.justincarmony.com/blog/2009/01/08/the-dangers-of-twitter/</guid>
		<description><![CDATA[Over Christmas my wife and I visited my father in San Diego, CA. Several members of my dad&#8217;s side of the family were there, and one day we had a discussion about being &#8220;wired.&#8221; What does that exactly mean? Well, how fast would a person respond after any form of electronic communication were to be ...


Related posts:<ol><li><a href='http://www.justincarmony.com/blog/2008/06/21/why-i-like-twitter/' rel='bookmark' title='Why I like Twitter'>Why I like Twitter</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Over Christmas my wife and I visited my father in San Diego, CA. Several members of my dad&#8217;s side of the family were there, and one day we had a discussion about being &#8220;wired.&#8221; What does that exactly mean? Well, how fast would a person respond after any form of electronic communication were to be sent.</p>
<p>We decided, that hands down, my father was the most wired. One evening my wife and I stayed in the car while my father ran into a grocery store to pick up something quickly. I made a tweet about our trip to Barnes &amp; Nobel, and how I spend so much money there. By the time my father came back to the car three minutes later, he commented to me about my tweet. He had set up that all my tweets are sent to his phone. I laughed and told him he definitely was the most wired.</p>
<p>Fast forward to January 8th, 2009, where I&#8217;m performing some database maintenance on the database for Dating DNA. For those who don&#8217;t know, I work for my father as the VP of Engineering for Dating DNA. Well, turns out that during the problem, one of the tables gets hosed. I had made 4 local backups and 2 off site backups (I&#8217;m paranoid, okay?). Turns out the off site backup to my local server at my home got corrupted during the transfer.</p>
<p>Being 1 AM, and none of my friends being online to congratulate me on my data redundancy, I hop on Twitter and post the following:</p>
<blockquote><p>Wow, I&#8217;m 100% grateful for database backups. *watches his boss freak at he gets this tweet*</p></blockquote>
<p>I then think that I better follow up so Kevin doesn&#8217;t totally freak. Within seconds I post this second tweet:</p>
<blockquote><p>Just an FYI Kevin (my boss), we&#8217;re 100% good, no problems <img src='http://c747925.r25.cf2.rackcdn.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p></blockquote>
<p>Before I can hit &#8220;update&#8221; I get a txt message from Kevin: &#8220;What happened???&#8221; I <strong><em>woke up</em></strong> my boss with the auto-txt from twitter, and made his heart skip a beat reading something about database backups from his VP of Engineering while he is working on DB maintenance.</p>
<p>Word of caution: know who is following your Twitter account! You might give your boss a heart attack!</p>


<p>Related posts:<ol><li><a href='http://www.justincarmony.com/blog/2008/06/21/why-i-like-twitter/' rel='bookmark' title='Why I like Twitter'>Why I like Twitter</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.justincarmony.com/blog/2009/01/08/the-dangers-of-twitter/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PHP Design &#8211; Biggest Database Oversights</title>
		<link>http://www.justincarmony.com/blog/2008/10/25/php-design-biggest-database-oversights/</link>
		<comments>http://www.justincarmony.com/blog/2008/10/25/php-design-biggest-database-oversights/#comments</comments>
		<pubDate>Sat, 25 Oct 2008 07:56:44 +0000</pubDate>
		<dc:creator>Justin Carmony</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Designs & Patterns]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://www.justincarmony.com/blog/?p=261</guid>
		<description><![CDATA[Over the last three years I&#8217;ve had the opportunity to work on several PHP projects, some of them having grown rapidly and required to scale quickly. Three in particular have been a fantastic learning experience for me. Now I don&#8217;t consider myself a total expert, but I thought I would share my experiences. Many PHP ...


Related posts:<ol><li><a href='http://www.justincarmony.com/blog/2008/03/07/five-common-php-design-patterns-that-arent-used-enough/' rel='bookmark' title='Five common PHP design patterns that aren&#8217;t used enough'>Five common PHP design patterns that aren&#8217;t used enough</a></li>
<li><a href='http://www.justincarmony.com/blog/2008/09/16/web-design-the-cookie-jar-when-dealing-with-clients/' rel='bookmark' title='Web Design &amp; The Cookie Jar: When Dealing with Clients'>Web Design &#038; The Cookie Jar: When Dealing with Clients</a></li>
<li><a href='http://www.justincarmony.com/blog/2008/07/01/mysql-php-sql_calc_found_rows-an-easy-way-to-get-the-total-number-of-rows-regardless-of-limit/' rel='bookmark' title='MySQL &amp; PHP  – SQL_CALC_FOUND_ROWS – An easy way to get the total number of rows regardless of LIMIT'>MySQL &#038; PHP  – SQL_CALC_FOUND_ROWS – An easy way to get the total number of rows regardless of LIMIT</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://c747925.r25.cf2.rackcdn.com/blog/wp-content/uploads/2008/10/database-vector.png"><img src="http://c747925.r25.cf2.rackcdn.com/blog/wp-content/uploads/2008/10/database-vector.png" alt="" title="database-vector" width="258" height="298" class="alignright size-full wp-image-600" /></a>
<p>Over the last three years I&#8217;ve had the opportunity to work on several PHP projects, some of them having grown rapidly and required to scale quickly. Three in particular have been a fantastic learning experience for me. Now I don&#8217;t consider myself a total expert, but I thought I would share my experiences. Many PHP developers are self-taught, like I was, and are learning PHP to be able to create dynamic websites. Many haven&#8217;t had studied or learned best practices for Object-Oriented Programming (OOP). They are web designers first, and programming in PHP is just a way to do things simple HTML can&#8217;t do.</p>
<p>Because most PHP applications rely heavily on the ability to read and store information in a database, many times designing how you interact with that database is critical. The reason being is if you design something, but don&#8217;t foresee a requirement or necessity, it can be extremely time consuming to go back and change. These &#8220;oversights&#8221; can be costly in time, money, and resources.</p>
<p>I&#8217;ve thought of some of the biggest oversights I&#8217;ve had when working with PHP and MySQL and put them in a list. This is my personal list, and I&#8217;m sure some people can think of some other oversights that belong on the list as well. This list is just for PHP &amp; MySQL, not PHP and any database. I know many people like using software like <a href="http://www.doctrine-project.org/">Doctrine</a> to allow switching between different database types. That is beyond the scope of this article.</p>
<p>Many of the examples in this article are very simple and are designed for showing techniques of better programming, not for actual use. Straight copy and paste most likely will not create sound, robust solutions. Search the web for a solid MySQL PHP Class to handle these issues for you, or you can make your own.</p>
<p>Now that I&#8217;ve thrown out my disclaimers and thoughts, lets venture on to by list:</p>
<p><strong></p>
<ul>
<li>Oversight #1 &#8211; No Data Access Layer</li>
<li>Oversight #2 &#8211; Design for Only One Database Connection</li>
<li>Oversight #3 &#8211; No Developer Logging</li>
<li>Oversight #4 &#8211; Queries Written In Procedural Processes</li>
<li>Oversight #5 &#8211; No Separation of Reads &#038; Writes</li>
</ul>
<p></strong></p>
<h2>Oversight #1 &#8211; No Data Access Layer</h2>
<p>I first heard the term Data Access Layer was when I was reading about ASP .NET. Basically a Data Access Layer (DAL) is a layer of code that you access data through. Sounds simple right? Many new php developers don&#8217;t have any type of DAL. Here is an example of not having a Data Access Layer:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

// Create MySQL Connection
$connection = mysql_connect('localhost', 'mysql_user', 'mysql_password');

// Query User List
$result = mysql_query(&quot;SELECT * FROM users&quot;, $connection);

// Get User List in an Array
$user_list = array();
while($user = mysql_fetch_assoc($result))
{
     $user_list[] = $user;
}

// Take the populated user list and display a table...
// ..

?&gt;
</pre>
<p>Now, that wasn&#8217;t so bad, was it? Lots of developers just use the mysql commands. I have several projects I worked on my early days with PHP that fall victim to this oversight. One in particular now has grown out of hand so bad that we&#8217;ve decided to start from scratch for a whole new version. Why? Lets say you have 3000+ php files, and your boss says &#8220;Hrm, we&#8217;re seeing some problems with performance. Can you display at the bottom of each page the # of queries you use on that page?&#8221; If you coded your entire project like the example above, you would be totally screwed. You would have to find each and every mysql_query() and add some counter at the end. It would be a managing Nightmare. So how cold you solve this problem?</p>
<pre class="brush: php; title: ; notranslate">

&lt;?php

// Declare MySqlDAL class
class MySqlDAL
{
     public $connection = null; // hold the connection link resource
     public $query_count = 0; // total number of queries executed

     // Connect when creating an instance of this class
     public function __construct($host, $user, $pass)
     {
          $this-&gt;connection = mysql_connect($host, $user, $pass);
          return true;
     }

     // Run a query against the database. The key here is to make sure
     // every query command goes through this function
     public function Query($sql)
     {
          // Execute Query &amp; Get Result Resource
          $result = mysql_query($sql);

          // Increment Query Counter
          $this-&gt;query_count++;

          // Return the result
          return $result;
     }

     // Function to take an SQL query, execute it, and return all
     // the rows in an assoc. array.
     public function FetchArray($sql)
     {
          // Execute the Query and get the Result
          $result = $this-&gt;query($sql);

          // Create Empty Array to Store all the rows
          $array = array();

          // Loop through each row
          while($row = mysql_fetch_assoc($result))
          {
               // Add the row to the array
               $array[] = $row;
          }

          // Return the array containing all the rows
          return $array;
     }
}

$dal = new MySqlDAL('localhost','mysql_user','mysql_pass');
$user_list = $dal-&gt;FetchArray(&quot;SELECT * FROM users&quot;);

// Display Table of Users...
// ..

?&gt;
</pre>
<p>First of all, you&#8217;ve satisfied the boss&#8217;s wish of keeping a counter for the total # of queries. The trick is to have all queries go through the function &#8220;Query($sql).&#8221; This will ensure the counter stays current. You can also add code to catch errors, display error messages, log queries, etc. Having a class to wrap around your database connection, queries, etc. can make your life easier, and more simple.</p>
<p><span id="more-261"></span><br />
<h2>Oversight #2 &#8211; Design for Only One Database Connection</h2>
<p>I have a project that I&#8217;ve taken over right now that is suffering from being programmed into handling only one database connection. &#8220;But why would you ever need to connect to more than one database?&#8221; Well, I like to have a database for important information: invoices, users, payments, etc. Stuff that is updated every day &#038; information that the end user manipulates. Then I like to have another database for logging statistical information: user log-ins, page hits, visitor counts. The problem I&#8217;ve ran into lately is I want to have hourly backups for my important information, but only daily backups for simple statistical information. It would be much easier if they were separated in different databases, but many times they are in the same. I don&#8217;t want to take the extra time and space to backup the statistical information.</p>
<p>Many people who run into this problem use a <a href="http://en.wikipedia.org/wiki/Singleton_pattern">Singleton class</a> to handle their Data Access Layer. A singleton class is a class that can only have one instance at a time in execution. This can be suer easy and quick to use in your code, but may lock you into a situation where your code only handles a single database connection:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

// I've declared a singleton class called MyDB.

$users = MyDb::FetchArray(&quot;SELECT * FROM users&quot;);

// ..

?&gt;
</pre>
<p>Now your boss comes in and asks you to connect to another database to get a list of customers. You think &#8220;uh oh, I can&#8217;t really do that with my design, now can I?&#8221; The solution I like to use is having Database Connection classes, and then a Database Connection Manager. Imagine I have the MySqlDAL class from the previous example in oversight #1. I would create singleton class called MySqlManager. It&#8217;s job would be to handle the creation &#038; management of all it&#8217;s classes. Here is an example: </p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

// ... declare my MySqlDAL class before

// Handles the creation and management of MySQL Connections
class MySqlManager
{

    // Holds the singleton instance
    private static $instance = null;

    // Contians each MySqlDAL object created;
    private $connections;

    private function __construct()
    {
        // Its private to prevent creation outside of the GetInstance function
        $this-&gt;connections = array();
    }

    public static function GetInstance()
    {
        // If the instance is null, make one
        if(!self::$instance)
        {
            self::$instance = new MySqlManager();
        }

        return self::$instance;
    }

    // Connect to a new database;
    public static function CreateConnection($host, $user, $pass, $name = 'default')
    {
        $manager = self::GetInstance();
        $manager-&gt;connections[$name] = new MySqlDAL($host, $user, $pass);

        return $manager-&gt;connections[$name];
    }

    public static function GetConnection($name = 'default')
    {
        $manager = self::GetInstance();
        if(isset($manager-&gt;connections[$name]))
        {
            return $manager-&gt;connections[$name];
        }
        else
        {
            // handle connection not found error...
        }
    }
}

// Now you can create a connection, and if you don't give it a name, it will be defaulted for you

$dal = MySqlManager::CreateConnection('localhost','mysql_user','mysql_pass', 'customer');

$customer_dal = MySqlManager::CreateConnection('mysql.another-location.com','another_user','another_pass');

// ..

// later in your code, maybe even in a class or function you could get the connection by name:

// get default connection
$dal = MySqlManager::GetConnection();

// Get customer database connection
$customer_dal = MySqlManager::GetConnection('customer');

$users = $dal-&gt;FetchArray('SELECT * FROM users');

$customers = $customer_dal-&gt;FetchArray(&quot;SELECT * FROM customers&quot;);

// ..

?&gt;
</pre>
<p>Now you have a MySQL Connection Manager class that can handle the creation, management, and disconnection of your SQL connections. Your boss will be happy to hear you can connect to another database with easy!</p>
<h2>Oversight #3 &#8211; No Developer Logging</h2>
<p>There are many times where I wish I could what was going on behind the scenes. It is very easy to add Query Logging to your Data Access Layer if you choose. I won&#8217;t give an example how to do so, but there are some several very important parts to it. First, you need to be able to enable &#038; disable query logging. Second, you should log whether it was successful or not. Also,  if you play around with PHP&#8217;s back tracing abilities you can trace where each query was made. I&#8217;ll make a blog post about this another day. </p>
<h2>Oversight #4 &#8211; Queries Written In Procedural Processes</h2>
<p>I absolutely *loathe* when I get into a situation where queries are being written all over the place. If there is one constant in any software development, it is that things will always change. When queries are being placed in procedural code, it makes management of database changes a total hassle. &#8220;But what about find and replace?&#8221; That can help you find places where you need to change, but you still can miss other places in your code, which can lead to bugs, headaches, and self-combustion. Here is an example: </p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

// .. code displaying a user profile:

// Get user links
$links = $dal-&gt;FetchArray(&quot;SELECT * FROM user_links WHERE user_id = 1 ORDER BY number&quot;);

// Display them on links page...

// .. another page

// Get user links
$links = $dal-&gt;FetchArray(&quot;SELECT * FROM user_links ORDER BY number&quot;);

// Display them on profile page...

// .. another page

// Get user links
$links = $dal-&gt;FetchArray(&quot;SELECT * FROM user_links ORDER BY number&quot;);

// Display them on about me page...

?&gt;
</pre>
<p>Not seeing the big issue here? Lets say you copy and paste that line of code &#8216;$links = $dal->FetchArray(&#8220;SELECT * FROM user_links ORDER BY id&#8221;);&#8217; on twenty different pages. Then your boss comes and says &#8220;Hey, you know how the user_links table has a title? Well every where we display the title, I&#8217;d like to have it show which # of link it is, so example: Link #1 &#8211; My Blog, Link #2 &#8211; My Facebook., Oh, and can we order them by date_added? Thanks!&#8221;</p>
<p>Have fun trying to find every place that query is executed. Don&#8217;t be surprised when only 80% of the queries get changed, and the other 20% become bug tickets with your boss wondering why you didn&#8217;t find them before. This is an example of writing queries all over the place when you need them, instead of organizing them and abstracting them by Classes and Functions. Here is an example of abstracting the query:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

class User
{
   public $id; // contains user_id 

   // ..

    public function GetVideos()
    {
        $dal = MySqlManager::GetInstance();
        $videos = $dal-&gt;FetchArray(&quot;SELECT * FROM user_videos WHERE user_id = '$this-&gt;id' ORDER BY date_added&quot;);

        $new_video_list = array();
        foreach($videos as $video)
        {
            $video['caption'] = &quot;Link #&quot;.$video['number'].' - '.$video['caption'];
            $new_video_list[] = $video;
        }

        return $new_video_list;
    }

    // ..
}

$user = new User(1);

$user_videos = $user-&gt;GetVideos();

// ..

?&gt;
</pre>
<p>Now your boss will give you a raise when you can make changes this quickly. While this example may seem simple, there are many times where I&#8217;ve had projects that queries have required major changes and re-writes. Bugs quickly service if queries that are the same, or similar, are copied and re-copied all over the place. This leads to a giant mess very quickly. So remove queries from the procedural flow of things by abstracting them in classes and functions.</p>
<h2>Oversight #5 &#8211; No Separation of Reads &amp; Writes</h2>
<p>This oversight has stung me for the first time just a few weeks ago. A project of mine had reached critical mass with its size, and out grew its beefy MySQL dedicated server. I started investigating doing a Master-Slave replication system, but every article said I needed to route SELECT statements to the slave servers, and just about every else to the Master (like Insert, Update, Delete, etc). This project didn&#8217;t have any Data Access Layer at all, and 2+ years of development on it. There is no way I could go back and re-write all the queries on budget and timeline, especially without causing bugs. especially if Insert/Update/Delete commands on accidently got routed to a slave server.</p>
<p>My suggestion is funneling all queries into two functions, Select() and Execute(). Then, when you create a MySqlDAL instance, it would actually have a $this->master_connection; and $this->slave_connection; It wouldn&#8217;t connection on creation, but on the first instance a query was executed. This is done to release stress on the Master server, the whole purpose of Master-Slave replication setups. Here is a mock class that would handle this:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

class MySqlDAL
{
    public $master_connection;
    public $master_host;
    public $slave_connection;
    public $slave_host;
    public $user;
    public $pass;

    // ..

    public function Select($sql)
    {
        if(!$this-&gt;slave_connection)
        {
            $this-&gt;ConnectSlave();
        }
        // .. Increment Slave Counter ..

        return $this-&gt;Query($sql, $this-&gt;slave_connection);
    }

    public function Execute($sql)
    {
        if(!$this-&gt;master_connection)
        {
            $this-&gt;ConnectMaster();
        }

        // .. Increment Master Counter ..

        return $this-&gt;Query($sql, $this-&gt;master_connection);
    }

    // ..   

}

?&gt;
</pre>
<h2>Conclusion</h2>
<p>Hopefully these insights into oversights with PHP and MySQL can help someone out there tackle there next project, big or small. If you have any questions, feel free to leave a comment and I&#8217;ll respond as soon as possible.</p>


<p>Related posts:<ol><li><a href='http://www.justincarmony.com/blog/2008/03/07/five-common-php-design-patterns-that-arent-used-enough/' rel='bookmark' title='Five common PHP design patterns that aren&#8217;t used enough'>Five common PHP design patterns that aren&#8217;t used enough</a></li>
<li><a href='http://www.justincarmony.com/blog/2008/09/16/web-design-the-cookie-jar-when-dealing-with-clients/' rel='bookmark' title='Web Design &amp; The Cookie Jar: When Dealing with Clients'>Web Design &#038; The Cookie Jar: When Dealing with Clients</a></li>
<li><a href='http://www.justincarmony.com/blog/2008/07/01/mysql-php-sql_calc_found_rows-an-easy-way-to-get-the-total-number-of-rows-regardless-of-limit/' rel='bookmark' title='MySQL &amp; PHP  – SQL_CALC_FOUND_ROWS – An easy way to get the total number of rows regardless of LIMIT'>MySQL &#038; PHP  – SQL_CALC_FOUND_ROWS – An easy way to get the total number of rows regardless of LIMIT</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.justincarmony.com/blog/2008/10/25/php-design-biggest-database-oversights/feed/</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using memcached
Database Caching 18/45 queries in 0.015 seconds using memcached
Content Delivery Network via Rackspace Cloud Files: c747925.r25.cf2.rackcdn.com

Served from: www.justincarmony.com @ 2012-02-07 21:03:01 -->
