<?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>use strict ;#) &#187; MySQL</title>
	<atom:link href="http://usestrict.net/category/mysql/feed/" rel="self" type="application/rss+xml" />
	<link>http://usestrict.net</link>
	<description>Vinny&#039;s Technical Corner</description>
	<lastBuildDate>Wed, 14 Jul 2010 20:21:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
		<item>
		<title>PHP+PDO+MySQL: How I&#8217;m doing it and a question&#8230;</title>
		<link>http://usestrict.net/2009/08/13/phppdomysql-how-im-doing-it-and-a-question/</link>
		<comments>http://usestrict.net/2009/08/13/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's the closest thing to the DBI that I found for PHP - and the reason for PHP is that it's just plain simpler than using pure Perl, and I don't have the time to learn Catalyst or some other Perl Web framework.</p>
<p>Anyway, here's what I'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>'ing and <code>execute</code>'ing the queries, and returning the data. Here'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'm calling <code>getStudentById()</code> at the beginning of <code>updateStudentById()</code>. It's OK - 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 - 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's the question part:<br />
Unfortunately, I couldn'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/13/phppdomysql-how-im-doing-it-and-a-question/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>myWebChat: IM with your site&#8217;s visitors</title>
		<link>http://usestrict.net/2009/03/11/mywebchat-im-with-your-sites-visitors/</link>
		<comments>http://usestrict.net/2009/03/11/mywebchat-im-with-your-sites-visitors/#comments</comments>
		<pubDate>Wed, 11 Mar 2009 13:57:45 +0000</pubDate>
		<dc:creator>Vinny</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[myWebChat]]></category>
		<category><![CDATA[newbies]]></category>
		<category><![CDATA[chat]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[web chat]]></category>

		<guid isPermaLink="false">http://usestrict.net/?p=280</guid>
		<description><![CDATA[Info regarding new Web Chatting application which allows site owners to interact with their visitors in real time.]]></description>
			<content:encoded><![CDATA[<p>I once saw a comment on AlphaInventions saying that the user would find it very nice if they could know who was visiting their blog and could talk to them in real time.</p>
<p>That, along with the ChatterBox in <a href="http://www.perlmonks.org" target="_blank">Perlmonk</a>'s website gave me the idea:  why not build a ChatterBox-like application that bloggers could use as a widget and regular sites could have as a pop-up or as  an embedded frame/div?</p>
<p>I did some digging and all I could find were apps that needed installation or were built in heavy Java. So I started out on my own project, which I called myWebChat (because it was <em>my</em> Web Chat application, of course <img src='http://usestrict.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  ).</p>
<p>Well, several weeks later (perhaps a few months with all the stuff I have going on), I am proud to announce <a href="http://mywebchat.usestrict.net" target="_blank">myWebChat version 0.2 and the hot-site</a>.</p>
<p>The funcionality is still pretty basic, but will allow you to talk to anyone who enters the chat with their username (no password required yet). It's like having an open chat room in your own website.</p>
<h3>What it is:</h3>
<ul>
<li><strong>It's a chat application</strong> that stays hosted on our servers, but <strong>shows on your website</strong> - you just need to add a snippet of code to your page.</li>
<li><strong>It's free</strong>: as in beer - you don't pay anything to use it on one domain. However, since I also need to pay my bills, I accept donations for the free version, which can also work as payment for the premium version. The main difference between the free and premium versions is a Google Ad on the Gui.</li>
<li><strong>It's light</strong>: built using Ajax, having MySQL and PHP on the server side, it's as light and fast as it gets...</li>
<li><strong>It's throughput friendly</strong>: in order to get the closest to real-time chatting possible without sending hundreds of requests per minute, it optimizes each call to the server by sleeping on the server side in case it doesn't find any new messages. The end result is less connection initiations, which means less throughput, which means that your hosting company won't get rich on your expense.</li>
<li><strong>It's safe</strong>: all my coding was done having safety in mind. If you find a bug, please do feel free to send me an email or add it to the Wish List page on the hot-site.</li>
<li><strong>It's cross-browser friendly</strong>: tested on Mozilla Firefox and MS IE. Seriously, why <strong>doesn't</strong> MS follow the standards?! Web developers should stop hacking their code to get it to work with IE's non-complience. But that's subject for another topic... this is not the place to rant.</li>
<li><strong>It's easy to install</strong>: follow the steps on the <a href="http://mywebchat.usestrict.net/install.php" target="_blank">Install</a> page to get your ChatMasterId and post the &lt;IFRAME&gt; code on the page you want it to show. That's it.</li>
<li><strong>It's multi-lingual</strong>: So far the site and the app come in 2 languages: English and Brazilian Portuguese. French is in the making and should be available in the next couple of weeks. If you'd like to see it in another language and would like to help out, <a href="http://mywebchat.usestrict.net/contact.php">get in touch</a>.</li>
</ul>
<h3>What it's NOT:</h3>
<ul>
<li><strong>It's NOT</strong> something that needs to be downloaded and installed in each client machine.</li>
<li><strong>It's NOT</strong> something that you as a webmaster will have to download into your site's filesystem. All it takes is a snippet of code that you get from our <a href="http://mywebchat.usestrict.net">hot-site</a>.</li>
<li><strong>It's NOT</strong> an application that talks to existing IM software such as MSN, Yahoo!, Skype... but who knows, given enough incentive, it might one day become it.</li>
</ul>
<h3><strong>Pre-requisites:</strong></h3>
<ul>
<li>A modern web browser;</li>
<li>Javascript enabled;</li>
<li>Cookies enabled;</li>
</ul>
<p>Please let me know what you think of this app either here or preferably at the <a href="http://mywebchat.usestrict.net/wish_list.php" target="_blank">Wish List</a> page, or send me a message through the <a href="http://mywebchat.usestrict.net/contact.php">contact form</a>. Your opinion is important!</p>
<p><em><strong>Note:</strong> I'm having some issues with emails on the server I hosted the app in, and will be changing hosts pretty soon. Please be patient if it takes me a while to reply to any emails sent from the contact form, and ping me here if I don't reply at all - since it probably means I didn't get your email.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2009/03/11/mywebchat-im-with-your-sites-visitors/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MySQL: MySQL for starters</title>
		<link>http://usestrict.net/2008/12/01/mysql-mysql-for-starters/</link>
		<comments>http://usestrict.net/2008/12/01/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'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's what I believe people start with - it'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-4"></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'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 -- A Learner'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><center><script type="text/javascript"><!--
google_ad_client = "pub-3864472231411838";
google_ui_features = "rc:0";
google_ad_width = 468;
google_ad_height = 60;
google_ad_format = "468x60_as";
google_ad_type = "text_image";
google_color_border = "{{color-border}}";
google_color_bg = "{{color-bg}}";
google_color_link = "{{color-title}}";
google_color_text = "{{color-text}}";
google_color_url = "{{color-link}}";

//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</center></p>
<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'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'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 "Configure the MySQL Server Now". Leave it checked. It'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's the recommended selection for modern Windows versions. You can change the Service Name to your liking. Also consider checking the "Include Bin Directory in Windows PATH" 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're only setting up a server for development and testing, or if you're not behind a firewall (you <em>ARE</em> behind a firewall, right?), then don't check the option to "Enable root access from remote machines". Once you fill in your new password and confirmation, you'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'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's the recommended selection for modern Windows versions. You can change the Service Name to your liking. Also consider checking the "Include Bin Directory in Windows PATH" 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're only setting up a server for development and testing, or if you're not behind a firewall (you <em>ARE</em> behind a firewall, right?), then don't check the option to "Enable root access from remote machines". Once you fill in your new password and confirmation, you'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't get me wrong - 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 "next, next, next, finish", 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>
<p><center><script type="text/javascript"><!--
google_ad_client = "pub-3864472231411838";
google_ui_features = "rc:0";
google_ad_width = 468;
google_ad_height = 60;
google_ad_format = "468x60_as";
google_ad_type = "text_image";
google_color_border = "{{color-border}}";
google_color_bg = "{{color-bg}}";
google_color_link = "{{color-title}}";
google_color_text = "{{color-text}}";
google_color_url = "{{color-link}}";

//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</center></p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2008/12/01/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/28/mysql-insert-into-on-duplicate-key-update/</link>
		<comments>http://usestrict.net/2008/11/28/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'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't there, otherwise, do the update.</p>
<p>That's when I found the "on duplicate key update" 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 'vinny' or 'vinny2', you'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 "on duplicate key update" 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>
<p><center><script type="text/javascript"><!--
google_ad_client = "pub-3864472231411838";
google_ui_features = "rc:0";
google_ad_width = 468;
google_ad_height = 60;
google_ad_format = "468x60_as";
google_ad_type = "text_image";
google_color_border = "{{color-border}}";
google_color_bg = "{{color-bg}}";
google_color_link = "{{color-title}}";
google_color_text = "{{color-text}}";
google_color_url = "{{color-link}}";

//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</center></p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2008/11/28/mysql-insert-into-on-duplicate-key-update/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
