<?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>UseStrict Consulting &#187; MySQL</title>
	<atom:link href="http://usestrict.net/tag/mysql/feed/" rel="self" type="application/rss+xml" />
	<link>http://usestrict.net</link>
	<description>Professional IT Solutions &#38; Training</description>
	<lastBuildDate>Sat, 12 May 2012 14:25:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>PHP+PDO+MySQL: How I&#8217;m doing it and a question&#8230;</title>
		<link>http://usestrict.net/2009/08/phppdomysql-how-im-doing-it-and-a-question/</link>
		<comments>http://usestrict.net/2009/08/phppdomysql-how-im-doing-it-and-a-question/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 12:47:18 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[PDO]]></category>
		<category><![CDATA[Select]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Update]]></category>

		<guid isPermaLink="false">http://usestrict.net/?p=832</guid>
		<description><![CDATA[Example of PHP+PDO+MySQL usage to select and update arbitrary fields. Only one prepared statement is used for updating the data.]]></description>
			<content:encoded><![CDATA[<p>I recently decided to rewrite an application that I created for an English school where I used to work, and this time I want to do it right. I chose to write it in PHP with Object Orientation in mind, and use PDO+MySQL for the DAO portion.</p>
<p>The reason for using PDO is that it&#8217;s the closest thing to the DBI that I found for PHP &#8211; and the reason for PHP is that it&#8217;s just plain simpler than using pure Perl, and I don&#8217;t have the time to learn Catalyst or some other Perl Web framework.</p>
<p>Anyway, here&#8217;s what I&#8217;m doing for the PDO portion.</p>
<p>First I created a <code>Db</code> class which is just a DB connection wrapper.</p>
<pre class="brush:php">
&lt;?php
class Db{

	public $dbh  = null;

	public function Db($db_type,$db_host,$db_user,
			         $db_pass,$db_base,$tbl_prefix){

		if ($db_type == 'mysql') { // in case I want to add oracle in the future

			$mysql_DSN = "mysql:host=".$db_host.";dbname=".$this->db_base;

			try {
				$this->dbh = new PDO($mysql_DSN, $db_user, $db_pass,
							   array(PDO::ATTR_PERSISTENT => true, PDO::ERRMODE_WARNING => true,
							         PDO::ATTR_ERRMODE => true));

			}
			catch(PDOException $e){
				$rc[msg] = $e->getMessage();
				die($rc[msg] . "  " . __LINE__);
			}

			return $this->dbh;

		}

	}

}
?&gt;
</pre>
<p>Secondly, I created the DAO classes which extend the DB. They are responsible for <code>prepare</code>&#8216;ing and <code>execute</code>&#8216;ing the queries, and returning the data. Here&#8217;s an example one (I stripped some bells and whistles in order to not confuse anyone):</p>
<pre class="brush:php">
&lt;?php
class StudentsDao extends Db {

	public $sth = array();

	// Constructor
	public function StudentsDao($db_type=NULL,$db_host=NULL,$db_user=NULL,
				  	       $db_pass=NULL,$db_base=NULL,$tbl_prefix=NULL) { // These params are to be passed to Db class

		// Connect to DB
		$this->Db($db_type,$db_host,$db_user,
			      $db_pass,$db_base,$tbl_prefix);

		// Prepares queries
		$this->sth = $this->prepare($tbl_prefix); // Look at prepare() further down

	} // end of function StudentsDao

	// Function that prepares queries
	public function prepare() {

		$sth = null; // will hold our temporary array

		// get all students
		$string = sprintf('select * from %s.%sstudents where id = ?',DB_BASE,TBL_PREFIX);	// I have these constants defined in the main page
		$sth['getStudentById'] = $this->dbh->prepare($string);

		// update Student by Id
		$string = sprintf('update %s.%sstudents
				   set field1 = ?, field2 = ?, field3 = ?
				   where id = ?',DB_BASE,TBL_PREFIX);	// Note that this table has 3 control fields (id, sys_creation_date, and sys_update_date)  prior to field1, field2, and field3 - I don't want them to be touched

		$sth['updStudentById'] = $this->dbh->prepare($string);

		return $sth;

	} // end of prepare()

	// Here we have the handlers for the queries prepared above.

	// Fetches all students
	public function getStudentById($id) {

		$s = $this->sth['getStudents'];
		$s->execute(array($id)) || die(print_r($s->errorInfo,1));
		$result = $s->fetchAll(PDO::FETCH_ASSOC);

		if (sizeof($result) == 0) {
			// no data found
			$out[err_cd] = 1;
		}
		else {
			// data was found
			$out[err_cd] = 0;
			$out[data] = $result;
		}

		return $out;

	}

	// Updates student by Id - this is a tricky one
	public function updateStudentById($data,$id){ // $data can have data regarding one or more fields

		// Populate current fields
		$fields = $this->getStudentById($id); // get current values

		// Remove unwanted fields
		$fields = array_slice($fields[data][0],3); // remove the 3 initial control fields

		// Replace with new fields
		foreach($data as $k=>$v){
			$fields[strtolower($k)] = $v;
		}
		$fields['id'] = $id;

		$s = $this->sth['updStudentById'];
		$s->execute(array_values($fields)) || die(print_r($s->errorInfo,1));
		$count = $s->rowCount();

		if ($count == 1) {
			$out[err_cd] = 0;
		}
		else {
			$out[err_cd] = -1;
		}
		$out[err_msg] = $this->status[$out[err_cd]];
		return $out;

	}
?&gt;
</pre>
<p>In the example above, you will probably frown on the fact that I&#8217;m calling <code>getStudentById()</code> at the beginning of <code>updateStudentById()</code>. It&#8217;s OK &#8211; I frown on it, too. Let me explain why I did that:</p>
<p>I wanted to be able to pass the function an associative array containing only the fields I want to update &#8211; be it only <code>field1</code>, or <code>field1</code> and <code>field2</code> and so on. But I wanted to do that against my already prepared query, and not touching any additional fields. In my application, <code>students</code> table has a BUNCH of fields. In other words, update any given field or set of fields using the single prepared statement, <strong>without</strong> having to set ALL the fields in <code>$data</code></p>
<p>My original idea was to basically, to emulate something like this:</p>
<p><code> update students set field1=field1, field2='some new value ', field3=field3 where id = 1</code></p>
<p>That would set <code>field1</code> to whatever value <code>field1</code> already had. </p>
<p><strong>Here&#8217;s the question part:<br />
Unfortunately, I couldn&#8217;t figure out how to do that using the PDO (how to bind a field name instead of a value against the <code>?</code>-mark). If you know how to do that, do leave a comment explaining how! <img src='http://usestrict.net/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /><br />
</strong></p>
<p>The technique shown in the example will basically pull all values from the record and populate them in the <code>$fields</code> array. The <code>array_slice()</code> is used to remove the control fields that I have in my table, and the rest gets compared against the <code>$data</code> array and if any matching fields are found in <code>$data</code>, those fields get their values assigned over the existing <code>$fields</code> values.</p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2009/08/phppdomysql-how-im-doing-it-and-a-question/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>MySQL: MySQL for starters</title>
		<link>http://usestrict.net/2008/12/mysql-mysql-for-starters/</link>
		<comments>http://usestrict.net/2008/12/mysql-mysql-for-starters/#comments</comments>
		<pubDate>Mon, 01 Dec 2008 20:18:59 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Starters]]></category>

		<guid isPermaLink="false">http://usestrict.wordpress.com/?p=292</guid>
		<description><![CDATA[Basic pointers for those who want to get started with MySQL]]></description>
			<content:encoded><![CDATA[<p>In this post I intend to give some pointers to those who are starting with RDBMS (Relational Database Management Systems) usage. I don&#8217;t intend to start any flame wars saying that this or that database is better, but simply to explain a few starter topics and point to some handy URLs. I chose MySQL because that&#8217;s what I believe people start with &#8211; it&#8217;s light, fast, has triggers and subselects, and it also has several options of neat front-ends. Keep reading if this has caught your attention.</p>
<p><span id="more-1020"></span></p>
<p><span style="color: #000000;"><strong>RDBMs (Relational Database Management Systems)</strong></span></p>
<p>RDBMs are programs designed to store and provide information in table format. Each system follows main standards but also includes unique features that others implement differently or not at all. They follow the client-server architecture. Each server will listen to a TCP/IP port (or Unix socket, but we&#8217;re not going that way here), and a client application (such as Toad for MySQL, Oracle SQL Developer, or phpMyAdmin) will connect to its port to manipulate its data.</p>
<p>The most famous RDBMs today are:</p>
<p><a href="http://www.oracle.com/technology/software/index.html" target="_blank">Oracle</a><br />
<a href="http://dev.mysql.com/downloads/" target="_blank">MySQL</a><br />
<a href="http://www.postgresql.org/download/" target="_blank">PostgreSQL</a><br />
<a href="http://www-01.ibm.com/software/data/db2/9/download.html" target="_blank">IBM DB2</a></p>
<p>Follow the links above to go to their respective download pages.</p>
<p>I believe most websites today are using MySQL databases, for its growing improvement with each version, its speed, reliability, and extensive documentation. It will be the focus of this post.</p>
<p><strong>Structured Query Language</strong></p>
<p>If you are looking into using any database in your applications, the least you need to know is some SQL.</p>
<p><a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.com%2F&amp;tag=usst-20&amp;linkCode=ur2&amp;camp=1789&amp;creative=9325">Amazon.com</a><img style="border:none !important; margin:0px !important;" src="http://www.assoc-amazon.com/e/ir?t=usst-20&amp;l=ur2&amp;o=1" border="0" alt="" width="1" height="1" /> has some books you can use for starters:</p>
<ul>
<li><a href="http://www.amazon.com/gp/product/0201596180?ie=UTF8&amp;tag=usst-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0201596180">Introduction to SQL: Mastering the Structured Query Language (3rd Edition)</a><img style="border:none !important; margin:0px !important;" src="http://www.assoc-amazon.com/e/ir?t=usst-20&amp;l=as2&amp;o=1&amp;a=0201596180" border="0" alt="" width="1" height="1" /></li>
<li><a href="http://www.amazon.com/gp/product/0596526849?ie=UTF8&amp;tag=usst-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0596526849">Head First SQL: Your Brain on SQL &#8212; A Learner&#8217;s Guide (Head First)</a><img style="border:none !important; margin:0px !important;" src="http://www.assoc-amazon.com/e/ir?t=usst-20&amp;l=as2&amp;o=1&amp;a=0596526849" border="0" alt="" width="1" height="1" /></li>
<li><a href="http://www.amazon.com/gp/product/0596007272?ie=UTF8&amp;tag=usst-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0596007272">Learning SQL (Learning)</a><img style="border:none !important; margin:0px !important;" src="http://www.assoc-amazon.com/e/ir?t=usst-20&amp;l=as2&amp;o=1&amp;a=0596007272" border="0" alt="" width="1" height="1" /></li>
</ul>
<p><strong>Installing MySQL server on Windows</strong></p>
<p>Installing MySQL server on Windows is a piece of cake. Follow these steps and there&#8217;s no getting it wrong:</p>
<ol>
<li>Download the latest stable MySQL server from <a href="http://dev.mysql.com/downloads/" target="_blank">here</a> (the link opens in a new window). The Community server is the Free (as in speech and as in beer) version. We&#8217;ll use the Windows Essentials Installer version.</li>
<li>Execute the .msi file, select the Typical install and do the <em>next, next, next</em> mantra. There will be a checkbox asking to &#8220;Configure the MySQL Server Now&#8221;. Leave it checked. It&#8217;s for the next step.</li>
<li>The <em>MySQL Server Instance Configuration Wizard</em> will be started. Click next to get started.</li>
</ol>
<p><em>Standard port (3306) install</em></p>
<ol>
<li>If your computer is not using TCP port 3306, then select the <em>Standard Configuration</em> radio button and click next. Read the section <em>Install for non-standard TCP port</em> if you need to use a different port.</li>
<li>You can have MySQL run as a Windows service. It&#8217;s the recommended selection for modern Windows versions. You can change the Service Name to your liking. Also consider checking the &#8220;Include Bin Directory in Windows PATH&#8221; checkbox. It will come in handy if you need to use the bundled MySQL command-line programs such as the client, mysqladmin, or mysqldump. Click next.</li>
<li>Set your root password to something safe. If you&#8217;re only setting up a server for development and testing, or if you&#8217;re not behind a firewall (you <em>ARE</em> behind a firewall, right?), then don&#8217;t check the option to &#8220;Enable root access from remote machines&#8221;. Once you fill in your new password and confirmation, you&#8217;ll be allowed to click Next.</li>
<li>Last step is to click Execute to start the configuration.</li>
</ol>
<p><em>Install for non-standard TCP port</em></p>
<ol>
<li>In the <em>MySQL Server Instance Configuration Wizard</em> select the <em>Detailed Configuration </em>radio button and click next.</li>
<li>You will have to select between <em>Developer Machine</em>, <em>Server Machine</em>, or <em>Dedicated MySQL Server</em> Machine. The difference is the amount of memory that will be allocated to the MySQL server. Select the Developer Machine for this tutorial.</li>
<li>MySQL allows you to select different engines according to your needs. MyISAM is the first engine that was released to the public. It has no support for transactions. InnoDB is the newer engine that supports transactions and subselects. It is not as fast as the MyISAM engine, but it&#8217;s much more powerful. Having said that, select the <em>Multifunctional Database</em> option and click Next.</li>
<li>Choose where you want to put your InnoDB drive. The default settings should be fine. Click Next.</li>
<li>For develpment and testing servers, the <em>Decision Support (DSS)/OLAP</em> selection in the Concurrent Connection screen should be fine.</li>
<li>You now have the chance to select which port you want listening to incomming connections. MySQL listens to port 3306 by default. You can add a firewall exception (again, you <em>ARE</em> behind a firewall, right?) by checking the appropriate box. Leave <em>Enable Strict Mode</em> checked. Click Next.</li>
<li>Select the character set most appropriate to your region. Latin1 does the trick in the west.</li>
<li>You can have MySQL run as a Windows service. It&#8217;s the recommended selection for modern Windows versions. You can change the Service Name to your liking. Also consider checking the &#8220;Include Bin Directory in Windows PATH&#8221; checkbox. It will come in handy if you need to use the bundled MySQL command-line programs such as the client, mysqladmin, or mysqldump. Click next.</li>
<li>Set your root password to something safe. If you&#8217;re only setting up a server for development and testing, or if you&#8217;re not behind a firewall (you <em>ARE</em> behind a firewall, right?), then don&#8217;t check the option to &#8220;Enable root access from remote machines&#8221;. Once you fill in your new password and confirmation, you&#8217;ll be allowed to click Next.</li>
<li>Last step is to click Execute to start the configuration.</li>
</ol>
<p><strong>MySQL clients</strong></p>
<p>As mentioned before, you will need a client to access your database. The server installations provide console clients such as Oracle sql*plus, and mysql command line tool. However, the visual clients are not only easy on the eyes, but they are a good way for you to learn by following the menu items (user management, table/database creation, views, triggers, etc). Now don&#8217;t get me wrong &#8211; command line manipulation is very important, but this post is for real beginners, right?</p>
<p>Some clients that I recommend:</p>
<p><a href="http://www.quest.com/toad-for-mysql/" target="_blank">Toad for MySQL</a><br />
<a href="http://www.webyog.com/en/downloads.php/" target="_blank">SQLYog</a> (for Linux users, installing it with Wine is just a case of &#8220;next, next, next, finish&#8221;, although they do have Linux binaries)<br />
<a href="http://dev.mysql.com/downloads/gui-tools/5.0.html">MySQL Administrator and Query Browser</a></p>
<p>Each client will give you detailed steps on how to install and configure them. Remember your MySQL server port, username, and password. You will need them during the setup phase.</p>
<p>Well, this is all I have to say about installing MySQL right now. In a future post I will discuss LAMP/WAMP, and some MySQL techniques that I find useful.</p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2008/12/mysql-mysql-for-starters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MySQL: Insert into &#8230; on duplicate key update</title>
		<link>http://usestrict.net/2008/11/mysql-insert-into-on-duplicate-key-update/</link>
		<comments>http://usestrict.net/2008/11/mysql-insert-into-on-duplicate-key-update/#comments</comments>
		<pubDate>Sat, 29 Nov 2008 00:36:03 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://usestrict.wordpress.com/?p=275</guid>
		<description><![CDATA[Handy syntax to work around primary key violations]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently working on a project and came across the need to decide between inserting or updating a record in a MySQL table using PHP. The first thing that came to mind was to do a select and do the insert if my key wasn&#8217;t there, otherwise, do the update.</p>
<p>That&#8217;s when I found the &#8220;on duplicate key update&#8221; for inserts. It basically does the if/else logic in one clean SQL sweep. This is how it works:<span id="more-24"></span></p>
<div style="border:1px dotted black;background-color:#ffffcc;width:80%;margin-left:15px;">
<div style="margin-left:20px;"><tt><br />
<span style="color:#009900;">-- Create a table and set a unique or primary key:</span></p>
<p>create table mytest (<br />
&nbsp;&nbsp;&nbsp;&nbsp;uname varchar(15) primary key  not null,<br />
&nbsp;&nbsp;&nbsp;&nbsp;age int(3)<br />
);</p>
<p><span style="color:#009900;">-- Insert some data</p>
<p>insert into mytest VALUES<br />
&nbsp;&nbsp;&nbsp;&nbsp;('vinny',32),<br />
&nbsp;&nbsp;&nbsp;&nbsp;('vinny2', 23);</p>
<p></span></tt></div>
</div>
<p>Now if you try to insert another record having uname either &#8216;vinny&#8217; or &#8216;vinny2&#8242;, you&#8217;ll get the following error:</p>
<div style="border:1px dotted black;background-color:#ffffcc;width:80%;margin-left:15px;">
<div style="margin-left:20px;"><tt><br />
insert into mytest VALUES ('vinny',33);</p>
<p><em>Error Code : 1062<br />
Duplicate entry 'vinny' for key 1<br />
(0 ms taken)</em></p>
<p></tt></div>
</div>
<p>To avoid that, use the &#8220;on duplicate key update&#8221; syntax:</p>
<div style="border:1px dotted black;background-color:#ffffcc;width:80%;margin-left:15px;">
<div style="margin-left:20px;"><tt><br />
insert into mytest VALUES ('vinny',33)<br />
on duplicate key update age=age+1;</p>
<p></tt></div>
</div>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2008/11/mysql-insert-into-on-duplicate-key-update/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

