<?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>scriptNode &#187; mysql</title>
	<atom:link href="http://scriptnode.com/tag/mysql/feed/" rel="self" type="application/rss+xml" />
	<link>http://scriptnode.com</link>
	<description>Tips and tricks for web developers.</description>
	<lastBuildDate>Tue, 01 Sep 2009 18:46:41 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>MySQL Database Class</title>
		<link>http://scriptnode.com/article/mysql-database-class/</link>
		<comments>http://scriptnode.com/article/mysql-database-class/#comments</comments>
		<pubDate>Mon, 25 Aug 2008 04:19:11 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[script-sunday]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=76</guid>
		<description><![CDATA[
I&#8217;ve been spending loads of time recently with a new project that&#8217;s supposed to be comprised mostly of
what I love doing the most: hardcore JavaScript.
Unfortunately, most front-ends aren&#8217;t much without a back-end to fall on, so I&#8217;ve had to hit the PHP pretty hard too.


When modifying the framework I had built, I noticed that the [...]]]></description>
			<content:encoded><![CDATA[<p>
I&#8217;ve been spending <strong>loads</strong> of time recently with a <a href="http://valadria.com/">new project</a> that&#8217;s supposed to be comprised mostly of<br />
what I love doing the most: hardcore <a href="/tag/javascript/">JavaScript</a>.<br />
Unfortunately, most front-ends aren&#8217;t much without a back-end to fall on, so I&#8217;ve had to hit the <a href="/tag/php">PHP</a> pretty hard too.
</p>
<p>
When modifying the framework I had built, I noticed that the old database class I was using was a little out of date. PHP5 is the new standard, shouldn&#8217;t we all<br />
be using <a href="http://us3.php.net/manual/en/book.pdo.php" title="PHP Data Object">PDO</a>? So I added migrating to PDO to my to-do list. But really, the class<br />
is a pretty good one. It&#8217;s certainly been <a href="http://dirtybeta.com/">useful</a> to me for, well, almost a few years now, give or take a few dozen tweaks.
</p>
<p>
So given the longevity of the script, I thought I&#8217;d offer it up for this week&#8217;s <a href="/tag/script-sunday/">Script Sunday</a>:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
/**<br />
 * Database constructor<br />
 */<br />
class Database {</p>
<p>	protected<br />
		$connection,<br />
		$debug,<br />
		$debug_func;</p>
<p>	/**<br />
	 * Constructor method. Connects to the database<br />
	 * @public<br />
	 */<br />
    function __construct() {</p>
<p>		$this-&gt;debug = Array();<br />
		$this-&gt;debug_func = &#8216;debugNone&#8217;;</p>
<p>    }</p>
<p>	/**<br />
	 * Gets the number of affected rows from the last query<br />
	 * @return integer Number of affected rows<br />
	 * @public<br />
	 */<br />
    function affectedRows() {<br />
        return mysql_affected_rows($this-&gt;connection);<br />
    }</p>
<p>	/**<br />
	 * Checks a table to see if a key/value pair exists<br />
	 * @param string table The table to check<br />
	 * @param string field The field in the table<br />
	 * @param string value The value of the field to check<br />
	 * @return bool Returns true if it found a matching row<br />
	 * @public<br />
	 */<br />
    function checkField($table, $field, $value, $and = &#8221;) {</p>
<p>		$qry = sprintf(&#8217;<br />
			SELECT<br />
				%s<br />
			FROM<br />
				%s<br />
			WHERE<br />
				%s = &#8220;%s&#8221;<br />
				%s<br />
			&#8216;,<br />
			$field,<br />
			$table,<br />
			$field,<br />
			$value,<br />
			$and<br />
		);</p>
<p>        $res = $this-&gt;query($qry);<br />
		$row = $this-&gt;fetchRow($res);</p>
<p>        return ($row ? true : false);</p>
<p>    }</p>
<p>	/**<br />
	 * Cleans a value for the DB<br />
	 * @param str $value The value to clean<br />
	 * @return str The cleaned string<br />
	 */<br />
	function clean($value) {</p>
<p>		$value = stripslashes($value);<br />
		$value = trim($value);<br />
		$value = str_replace(&#8221;&#8216;&#8221;, &#8220;\&#8217;&#8221;, $value);</p>
<p>		return $value;</p>
<p>	}</p>
<p>	/**<br />
	 * Connect to the database<br />
	 * @param string db_server The database server to connect to (often localhost)<br />
	 * @param string db_user The user to send to the server<br />
	 * @param string db_password The user&#8217;s password<br />
	 * @param string db_name The name of the database to use<br />
	 * @public<br />
	 */<br />
    function connect($db_server, $db_user, $db_password, $db_name) {</p>
<p>        $this-&gt;connection = mysql_connect($db_server, $db_user, $db_password);<br />
        $this-&gt;select($db_name, $this-&gt;connection);</p>
<p>        return ($this-&gt;connection ? true : false);</p>
<p>    }</p>
<p>	function debugNone() {}</p>
<p>	/**<br />
	 * Adds a debug message to $debug<br />
	 * @param str The debug message<br />
	 * @public<br />
	 */<br />
	function debugPut($debug) {<br />
		$this-&gt;debug[] = $debug;<br />
	}</p>
<p>	/**<br />
	 * Deletes rows from the database<br />
	 * @param string table The table to query<br />
	 * @param string where There WHERE clause in the query<br />
	 * @param integer limit How many rows to limit (default is 1)<br />
	 * @return integer Number of affected rows<br />
	 * @public<br />
	 */<br />
    function deleteRows($table, $where, $limit = 1) {</p>
<p>		$limit = ($limit ? &#8216;LIMIT &#8216; . $limit : &#8221;);</p>
<p>        $qry = &#8216;DELETE FROM &#8216; . $table . &#8216;<br />
				WHERE &#8216; . $where . &#8216;<br />
				&#8216; . $limit;</p>
<p>        $this-&gt;query($qry);</p>
<p>		return $this-&gt;affectedRows();</p>
<p>    }</p>
<p>	/**<br />
	 * Retrieves a row from the database<br />
	 * @param string result The result set returned from the query<br />
	 * @return array Associatve index of the retrieved row<br />
	 */<br />
    function fetchRow($res) {<br />
        return @mysql_fetch_assoc($res);<br />
    }</p>
<p>	/**<br />
	 * Get a single row from the database<br />
	 * @param qry The query to send<br />
	 * @return array Associative array of the row<br />
	 */<br />
	function getRow($qry) {</p>
<p>		$res = $this-&gt;query($qry);<br />
		$row = $this-&gt;fetchRow($res);</p>
<p>		return $row;</p>
<p>	}</p>
<p>	/**<br />
	 * Retreive rows from the database<br />
	 * @param qry The query to get the rows<br />
	 * @param array Numeric array of the rows<br />
	 */<br />
	function getRows($qry) {</p>
<p>		$rows = Array();<br />
		$res  = $this-&gt;query($qry);</p>
<p>		while ($row = $this-&gt;fetchRow($res)) {<br />
			$rows[] = $row;<br />
		}</p>
<p>		return $rows;</p>
<p>	}</p>
<p>	/**<br />
	 * Format a query for insertion into the database<br />
	 * @param string table The table to insert into<br />
	 * @param array pairs Key value pairs of the fields and values to insert<br />
	 * @return string The prepared query, ready to insert<br />
	 */<br />
    function formatInsert($table, $pairs) {</p>
<p>        foreach ($pairs as $field =&gt; $value) {</p>
<p>			$fields .= $field . &#8216;,&#8217;;</p>
<p>			if (!is_numeric($value)) {<br />
				$value = $this-&gt;clean($value);<br />
			}</p>
<p>			$values .= &#8220;&#8216;$value&#8217;,&#8221;;</p>
<p>        }</p>
<p>		$fields = substr($fields, 0, -1);<br />
		$values = substr($values, 0, -1);</p>
<p>		$qry = sprintf(&#8221;<br />
			INSERT INTO<br />
				$table<br />
			($fields)<br />
			VALUES<br />
				($values)<br />
		&#8220;);</p>
<p>        return $qry;</p>
<p>    }</p>
<p>	/**<br />
	 * Formats an update query based on a key/value array<br />
	 * @param string table The name of the table<br />
	 * @param array pairs The key/value pair of the fields/values<br />
	 * @param string where The WHERE clause of the array (default: 1)<br />
	 * @param integer limit The limit on tbe query<br />
	 * @return string The prepared query<br />
	*/<br />
    function formatUpdate($table, $pairs, $where = &#8216;1&#8242;, $limit = false) {</p>
<p>        foreach ($pairs as $key =&gt; $value) {</p>
<p>			if (!is_numeric($value)) {<br />
				$value = $this-&gt;clean($value);<br />
			}</p>
<p>			$set .= &#8220;$key = &#8216;$value&#8217;, &#8220;;</p>
<p>        }</p>
<p>        $set   = substr($set, 0, -2);<br />
		$limit = ($limit ? &#8216; LIMIT &#8216; . $limit : &#8221;);</p>
<p>		$qry = sprintf(&#8221;<br />
			UPDATE<br />
				$table<br />
			SET<br />
				$set<br />
			WHERE<br />
				$where<br />
			$limit<br />
		&#8220;);</p>
<p>        return $qry;</p>
<p>    }</p>
<p>	/**<br />
	 * Get the id of the last inserted row<br />
	 * @return integer They id (if it exists) of the last inserted row<br />
	*/<br />
    function getID() {<br />
        return mysql_insert_id($this-&gt;connection);<br />
    }</p>
<p>	/**<br />
	 * Inserts rows into the database<br />
	 * @param string table The table to send the query to<br />
	 * @param array pairs The key/value pairs to insert into the database<br />
	 * @return integer Number of affected rows<br />
	*/<br />
	function insertRows($table, $pairs) {<br />
		return $this-&gt;query($this-&gt;formatInsert($table, $pairs));<br />
	}</p>
<p>	/**<br />
	 * Gets the number of rows from a result set<br />
	 * @return integer Number of rows<br />
	*/<br />
    function numRows($res) {<br />
        return mysql_num_rows($res);<br />
    }</p>
<p>	/**<br />
	 * Send a query to the database<br />
	 * @param string qry The query to send<br />
	 * @return string A reference to the result set<br />
	*/<br />
    function query($qry) {</p>
<p>		$func = $this-&gt;debug_func;<br />
		$this-&gt;$func($qry);</p>
<p>        return mysql_query($qry, $this-&gt;connection);</p>
<p>    }</p>
<p>	/**<br />
	 * Select a database on the server<br />
	 * @param string db_name The name of the database<br />
	 * @return bool Returns true on success and false on failure<br />
	*/<br />
    function select($db_name, $connection = null) {</p>
<p>		if ($connection) {<br />
			$this-&gt;connection = &amp;$connection;<br />
		}</p>
<p>        return mysql_select_db($db_name, $this-&gt;connection);</p>
<p>    }</p>
<p>	/**<br />
	 * Turns on or off the debug option<br />
	 * @param bool debug The new value of the debug option<br />
	*/<br />
	function setDebug($debug) {<br />
		if ($debug) {<br />
			$this-&gt;debug_func = &#8216;debugPut&#8217;;<br />
		} else {<br />
			$this-&gt;debug_func = &#8216;debugNone&#8217;;<br />
		}<br />
	}</p>
<p>	/**<br />
	 * Updates rows in the database<br />
	 * @param string table The table to send the query to<br />
	 * @param array pairs The key/value pairs to insert into the database<br />
	 * @param string where The WHERE clause of the array (default: 1)<br />
	 * @param integer limit The limit on tbe query<br />
	 * @return integer Number of affected rows<br />
	*/<br />
	function updateRows($table, $pairs, $where = &#8216;1&#8242;, $limit = false) {<br />
		return $this-&gt;query($this-&gt;formatUpdate($table, $pairs, $where, $limit));<br />
	}</p>
<p>}<br />
</textarea></p>
<p>
And here&#8217;s a quick example of how to use it:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
$db = new Database();<br />
$db-&gt;connect($server, $user, $password, $db_name);</p>
<p>$query = &#8216;SELECT * FROM users&#8217;;<br />
$users = $db-&gt;getRows($query);</p>
<p>foreach ($users as $user) {<br />
	echo &#8216;Username: &#8216; . $user['username'] . &#8216;&lt;br&gt;&#8217;;<br />
}<br />
</textarea></p>
<ul>
<li><a href="/assets/php/db-class/database.php.txt">[Download database.php.txt]</a> (6,848 bytes)</li>
<li><a href="/assets/php/db-class/db-class.zip">[Download db-class.zip]</a> (1,966 bytes)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/mysql-database-class/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>My New Coding Habits</title>
		<link>http://scriptnode.com/article/my-new-coding-habits/</link>
		<comments>http://scriptnode.com/article/my-new-coding-habits/#comments</comments>
		<pubDate>Sun, 03 Aug 2008 05:24:30 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Novice]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=43</guid>
		<description><![CDATA[
I think any programmers worth their weight improve their practices and styles on a regular basis. I&#8217;ve noticed my code has changed drastically in the last year or so. It&#8217;s more organized, structured, and maintainable than it was, but I&#8217;ve also picked up what I think are some small but good changes:



No var in globals [...]]]></description>
			<content:encoded><![CDATA[<p>
I think any programmers worth their weight improve their practices and styles on a regular basis. I&#8217;ve noticed my code has changed <strong>drastically</strong> in the last year or so. It&#8217;s more organized, structured, and maintainable than it was, but I&#8217;ve also picked up what I think are some small but good changes:
</p>
<ol>
<li>
<h3>No <code>var</code> in globals (JavaScript)</h3>
<p>
I&#8217;d be lying if I said I <a href="http://yuiblog.com/blog/2008/04/16/global-domination-part-two/">wasn&#8217;t externally influenced</a> on this one. <a href="http://javascript.crockford.com/">Douglas Crockford</a> has a lot of great recommendations, and this is one I tend to agree with. When applicable and realistic, making your JavaScript code smaller is always a good thing. It means a faster download for your users which leads to a better user experience.
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Before:<br />
var scriptNode = {};</p>
<p>// After:<br />
scriptNode = {};<br />
</textarea>
</li>
<li>
<h3>Not abbreviating beyond readability</h3>
<p>
This is probably a lesson most programmers learned long ago. I went back to some of my older code recently, hoping to reuse it. The good news was that the code itself was written well enough that I could use it with minimal editing. The bad news was that I first had to figure out what many of the variables were for because they were so badly named:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Before:<br />
var setCoords = function(c, dir) {<br />
    var nc = {<br />
        x : c.x,<br />
        y : c.y<br />
    };<br />
    if (dir == &#8216;l&#8217;) {<br />
        nc.x&#8211;;<br />
    } else {<br />
        nc.x++;<br />
    }<br />
    return nc;<br />
};</p>
<p>// After:<br />
/**<br />
 * Set the coordinates based on direction<br />
 * @param {Object} coords An object with x/y keys<br />
 * @param {String} dir The direction [l, r]<br />
 * @return {Object} An x/y object with the new coordinates<br />
*/<br />
var setCoords = function(coords, dir) {<br />
    var newCoords = {<br />
        x : coords.x,<br />
        y : coords.y<br />
    };<br />
    if (dir == &#8216;l&#8217;) {<br />
        newCoords.x&#8211;;<br />
    } else {<br />
        newCoords.x++;<br />
    }<br />
    return newCoords;<br />
};<br />
</textarea></p>
<p>
I&#8217;m not suggesting <a href="http://en.wikipedia.org/wiki/Hungarian_notation">Hungarian notation</a>, but descriptive variable and function names are the way to go. You don&#8217;t want to hate yourself a month later (or for whoever is working with your code to hate you) when it needs to be maintained later. And thanks to tools like <a href="http://developer.yahoo.com/yui/compressor/">YUI Compressor</a>, even JavaScript files won&#8217;t be negatively affected by adding a few characters here and there.
</p>
</li>
<li>
<h3>CSS dashes instead of camelCase</h3>
<p>
The logic here is that a language should look like itself. I understand why I used to prefer camelCase; even minified CSS files can&#8217;t alter class names or IDs, so dashes make for a larger download. But when revisiting a file, it looks less alien when the nomenclature is cohesive. This makes everything easier.
</p>
<p><textarea class="css" cols="50" name="code" rows="10"><br />
/* Before: */<br />
.userOptions {<br />
    font-family: verdana, sans-serif;<br />
}<br />
div#mainCommentBubble {<br />
    background-image: url(bubble.gif);<br />
}</p>
<p>/* After: */<br />
.user-options {<br />
    font-family: verdana, sans-serif;<br />
}<br />
div#main-comment-bubble {<br />
    background-image: url(bubble.gif);<br />
}<br />
</textarea>
</li>
<li>
<h3>Leaning more towards <acronym title="Object Oriented">OO</acronym></h3>
<p>
Again, I think many programmers have learned this lesson already, and likewise I&#8217;ve been using these practices for a while now. The difference is that my code has become so much more maintainable that I preach these lessons often and have become something of an advocate of these patterns.
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Before:<br />
showError();<br />
toggleElement(content);<br />
hideError();</p>
<p>// After:<br />
error.show();<br />
content.toggle();<br />
error.hide();<br />
</textarea>
</li>
<li>
<h3>Clean, organized MySQL queries</h3>
<p>
Thoughout my entire programming career (more than four years now), I have constantly changed the way I organized MySQL queries in my PHP code. Recently I noticed that editing my older code was a pain in the ass, and I sought to change that. Adding a <code>WHERE</code> clause or an extra <code>SELECT</code> parameter should be an easy task, and the solution to me was to break each section into new lines, tabbing in the same manner that I did in my code blocks:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
// Much before:<br />
$qry = &#8217;select chats.*, users.username from chats, users where chats.room_id = &#8216; . $room_id . &#8216; and chats.user_id = users.user_id&#8217;;</p>
<p>// Before:<br />
$qry = sprintf(&#8217;SELECT chats.*, users.username<br />
FROM chats, users<br />
WHERE (chats.room_id = %s) AND (chats.user_id = users.user_id)&#8217;,<br />
$room_id);</p>
<p>// After:<br />
$qry = &#8221;<br />
    SELECT<br />
        chats.*,<br />
        users.username<br />
    FROM<br />
        chats,<br />
        users<br />
    WHERE<br />
        (chats.room_id = $room_id)<br />
        AND (chats.user_id = users.user_id)<br />
&#8220;;<br />
</textarea></p>
<li>
<h3>Using a Single Event Listener When Possible</h3>
<p>
<a href="http://www.quirksmode.org/js/introevents.html">Events</a> can be tricky. They can be the cause of <a href="http://javascript.crockford.com/memory/leak.html">memory leaks</a>, and having too many can bog browsers down. So when dealing with multiple instances of similar events, why not combine them? Events are not difficult to parse to figure out what happened to what:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Before:<br />
var handleClick = function(e) {<br />
    // Something useful here<br />
};</p>
<p>var el, container = document.createElement(&#8217;ul&#8217;);<br />
container.id = &#8216;container&#8217;;</p>
<p>for (var i = 0; i < 10; i++) {<br />
    el = document.createElement('li');<br />
    el.innerHTML = 'List item ' + i;<br />
    YAHOO.util.Event.addListener(el, 'click', handleClick);<br />
    container.appendChild(el);<br />
}</p>
<p>document.body.appendChild(container);</p>
<p>// After:<br />
var handleClick = function(e) {<br />
    var el = YAHOO.util.Event.getTarget(e);<br />
    if (el.nodeName == 'LI') {<br />
        // Something useful here<br />
    }<br />
};</p>
<p>var el, container = document.createElement('ul');<br />
container.id = 'container';</p>
<p>for (var i = 0; i < 10; i++) {<br />
    el = document.createElement('li');<br />
    el.innerHTML = 'List item ' + i;<br />
    container.appendChild(el);<br />
}</p>
<p>YAHOO.util.Event.addListener(container, 'click', handleClick);<br />
document.body.appendChild(container);<br />
</textarea>
</li>
</ul>
<p>
Small improvements like these can add up to make <strong>much</strong> better code. If you&#8217;re a developer and you haven&#8217;t noticed a positive change in your code in the last few months, I highly recommend reading up on useful patterns and practices.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/my-new-coding-habits/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
