<?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/"
xmlns:series="http://unfoldingneurons.com/"
><channel><title>David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞. &#187; MySQL</title> <atom:link href="http://davidwalsh.name/tutorials/mysql/feed" rel="self" type="application/rss+xml" /><link>http://davidwalsh.name</link> <description>Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</description> <lastBuildDate>Sun, 20 May 2012 22:40:48 +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>MooTools Star Ratings with&#160;MooStarRating</title><link>http://davidwalsh.name/mootools-star-rating</link> <comments>http://davidwalsh.name/mootools-star-rating#comments</comments> <pubDate>Tue, 08 Feb 2011 14:59:12 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[CSS]]></category> <category><![CDATA[MooTools]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5166</guid> <description><![CDATA[I&#8217;ve said it over and over but I&#8217;ll say it again:  JavaScript&#8217;s main role in web applications is to enhance otherwise boring, static functionality provided by the browser.  One perfect example of this is the Javascript/AJAX-powered star rating systems that have become popular over the past five years.  Star rating systems are attractive, allow us [...]<p><a
href="http://davidwalsh.name/mootools-star-rating">MooTools Star Ratings with&nbsp;MooStarRating</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<a
href="http://davidwalsh.name/dw-content/mootools-star-rating.php"><img
src="http://davidwalsh.name/dw-content/starRating.png" alt="MooTools Star Rating" class="image" /></a><p>I&#8217;ve said it over and over but I&#8217;ll say it again:  JavaScript&#8217;s main role in web applications is to enhance otherwise boring, static functionality provided by the browser.  One perfect example of this is the Javascript/AJAX-powered star rating systems that have become popular over the past five years.  Star rating systems are attractive, allow us to avoid ugly forms, and prevent unnecessary page reloads.  A new plugin by Lorenzo Stanco called <a
href="http://mootools.net/forge/p/moostarrating" rel="nofollow">MooStarRating</a> has hit the MooTools Forge and I wanted to share with you how to use it.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/mootools-star-rating.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>The&nbsp;HTML</h2><p>The star rating system uses an HTML form with radio buttons as the base:</p><pre class="html">
&lt;form name="ratingsForm"&gt;
    &lt;label&gt;Do you like this post?&lt;/label&gt;
    &lt;input type="radio" name="rating" value="0.5"&gt;
    &lt;input type="radio" name="rating" value="1.0"&gt;
    &lt;input type="radio" name="rating" value="1.5"&gt;
    &lt;input type="radio" name="rating" value="2.0"&gt;
    &lt;input type="radio" name="rating" value="2.5"&gt;
    &lt;input type="radio" name="rating" value="3.0"&gt;
    &lt;input type="radio" name="rating" value="3.5"&gt;
    &lt;input type="radio" name="rating" value="4.0"&gt;
    &lt;input type="radio" name="rating" value="4.5"&gt;
    &lt;input type="radio" name="rating" value="5.0"&gt;
    &lt;input type="radio" name="rating" value="5.5"&gt;
    &lt;input type="radio" name="rating" value="6.0"&gt;
    &lt;input type="radio" name="rating" value="6.5"&gt;
    &lt;input type="radio" name="rating" value="7.0" checked="checked"&gt;
    &lt;input type="radio" name="rating" value="7.5"&gt;
    &lt;input type="radio" name="rating" value="8.0"&gt;
    &lt;input type="radio" name="rating" value="8.5"&gt;
    &lt;input type="radio" name="rating" value="9.0"&gt;
    &lt;input type="radio" name="rating" value="9.5"&gt;
    &lt;input type="radio" name="rating" value="10.0"&gt;
	&lt;span id="htmlTip"&gt;&lt;/span&gt;
&lt;/form&gt;
</pre><p>Note the ID of the form and the name of the radio buttons &#8212; we&#8217;ll use those when creating our MooStarRating instance.  Also note that I&#8217;m creating &#8220;half&#8221; rating options, as well as using checked to note what the current average rating is.</p><h2>The&nbsp;CSS</h2><p>This plugin requires no additional CSS.  That&#8217;s a bonus as it&#8217;s one less server request.</p><h2>The MooTools&nbsp;JavaScript</h2><p>The first step in using MooStarRating is defining the image paths for the stars:</p><pre class="js">
// Configure the image paths
var MooStarRatingImages = {
	defaultImageFolder: "/js/mooStarRating/images",
	defaultImageEmpty:  "empty.png",
	defaultImageFull:   "full.png",
	defaultImageHover:  "hover.png"
};
</pre><p>Once the path and image names are defined, it&#8217;s time to create an instance of MooStarRating:</p><pre class="js">
// A fake post ID for the sake of submission
var postId = 10;

// When the DOM is ready....
window.addEvent("domready",function() {	
	// Create our instance
	var starRater = new MooStarRating({
		form: "ratingsForm",
		radios: "rating",
		half: true,
		//imageEmpty: "star_boxed_empty.png", // For setting special images
		//imageFull:  "star_boxed_full.png",
		//imageHover: "star_boxed_hover.png", 
		width: 17, 
		tip: "Rate as &lt;i&gt;[VALUE] / 10.0&lt;/i&gt;", 
		tipTarget: document.byId("htmlTip"),
		tipTargetType: "html"
	});
	
	// Listen for star clicks
	starRater.addEvent("click",function(value) {
		// Send ajax request to server
		new Request.send({
			url: "rating.php",
			data: { rating: value, postId: postId }
		});
	});
});

</pre><p>MooStarRating is loaded with options.  Here we pass the form ID and the name we provided to the radio buttons.  As I&#8217;m allowing half-stars, the <code>half</code> option is set to true.  MooStarRating also provides a &#8220;tip&#8221; functionality which allows a message to be displayed along side the star rating.  Lastly, the <code>click</code> event provides the user&#8217;s rating for which you may send an AJAX request to the server to save the rating.  Simple!</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/mootools-star-rating.php" class="demo">View Demo</a><div
class="clear"></div></div><p>That&#8217;s it!  I love this plugin because it&#8217;s simple and effective.  Big props go to Lorenzo Stanco for his excellent piece of work.  If there&#8217;s enough interest, I&#8217;ll create a tutorial that includes enough PHP and MySQL to get this rating system working with real data.</p><p><a
href="http://davidwalsh.name/mootools-star-rating">MooTools Star Ratings with&nbsp;MooStarRating</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/mootools-star-rating/feed</wfw:commentRss> <slash:comments>32</slash:comments> </item> <item><title>Quick Tip:  MySQL&#160;date_add</title><link>http://davidwalsh.name/mysql-date-add</link> <comments>http://davidwalsh.name/mysql-date-add#comments</comments> <pubDate>Thu, 20 May 2010 00:51:11 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[MySQL]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=4971</guid> <description><![CDATA[Here&#8217;s a quick MySQL tip I wanted to throw your way. I created an event system a while back and one of the requirements of the system was to show events that happened yesterday forward, meaning events older than 2 days were to be hidden. MySQL&#8217;s date_add will allow you to do just that: The [...]<p><a
href="http://davidwalsh.name/mysql-date-add">Quick Tip:  MySQL&nbsp;date_add</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p>Here&#8217;s a quick MySQL tip I wanted to throw your way.  I created an event system a while back and one of the requirements of the system was to show events that happened yesterday forward, meaning events older than 2 days were to be hidden.  MySQL&#8217;s <span
class="function">date_add</span> will allow you to do just that:</p><h2>The MySQL&nbsp;Example</h2><pre class="sql">
SELECT title, venue, url, city, state, DATE_FORMAT(date_starts,\'%b %e\') as formatted_date
FROM events
WHERE date_starts >= DATE_ADD(NOW(), INTERVAL -1 DAY) // yesterday!
ORDER BY date_starts ASC
</pre><p>Note that I&#8217;m using a negative date value.  You can use a positive date value to get tomorrow, next week, next month, etc..</p><p>I like the idea of showing events the from past few days &#8212; they show that there&#8217;s been action recently. <a
href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-add" rel="nofollow">Click here</a> for more about MySQL <span
class="function">date_add</span>.</p><p><a
href="http://davidwalsh.name/mysql-date-add">Quick Tip:  MySQL&nbsp;date_add</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/mysql-date-add/feed</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>Create Custom Element Property Getters and Setters with&#160;MooTools</title><link>http://davidwalsh.name/mootools-custom-element</link> <comments>http://davidwalsh.name/mootools-custom-element#comments</comments> <pubDate>Mon, 03 May 2010 12:15:08 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[MySQL]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=4961</guid> <description><![CDATA[One of the goals of the MooTools projects is to create very flexible methods by which developers may modify or extend the behavior of given classes. One example of that flexibility is the ability to customize the Element class&#8217; get and set methods for specified values. The default behavior of the get and set methods [...]<p><a
href="http://davidwalsh.name/mootools-custom-element">Create Custom Element Property Getters and Setters with&nbsp;MooTools</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p>One of the goals of the MooTools projects is to create very flexible methods by which developers may modify or extend the behavior of given classes.  One example of that flexibility is the ability to customize the Element class&#8217; <span
class="function">get</span> and <span
class="function">set</span> methods for specified values.</p><p>The default behavior of the get and set methods for an object are to return/modify the given Element attribute.  Take the following for example:</p><pre class="js">
var alt = document.id('myImage').get('title');  //returns the image's title attribute text
</pre><p>The above code modifies the title attribute for the given element.  Simple, of course, but then MooTools also uses the <span
class="function">get</span>/<span
class="function">set</span> methods to set and retrieve items that aren&#8217;t element attributes:</p><pre class="js">
var tag = document.id('myImage').get('tag'); //returns images's tag (img)
</pre><p>The above code retrieves the given element&#8217;s tag name.  How does MooTools do this?  Simple:  the <span
class="function">Element.Properties</span> object.  You can set custom get and set handling by adding your desired string to the <span
class="function">Element.Properties</span> object.  Here&#8217;s an example:</p><pre class="js">
Element.Properties.yourCustomGetOrSetName = {
	get: function() {
		//your custom programming to accomplish what should be returned...
		return yourReturnValue;
	},
	set: function(input) {
		//your custom programming to accomplish what should be set...
		//don't need to return anything
	},
	erase: function() { //erase works too!
		//programming to erase this
	}
};
</pre><p>Here&#8217;s the code MooTools uses internally to accomplish the <span
class="function">get(&#8216;tag&#8217;)</span> ability:</p><pre class="js">
Element.Properties.tag = {
	get: function(){
		return this.tagName.toLowerCase();
	}
};
</pre><p>So how could you use this?  You could use <span
class="function">Element.Properties</span> to create a <span
class="function">parent</span> getter:</p><pre class="js">
Element.Properties.parent = {
	get: function() {
		return this.getParent(); //returns the element's parent
	}
	//no need to do a setter or eraser
};
//.....
//usage
var parent = document.id('myElement').get('parent'); //returns myElement's parent element.
</pre><p>Pretty sweet, no?  Have any other items you&#8217;d like to see in the get or set methods?  Share!</p><p><a
href="http://davidwalsh.name/mootools-custom-element">Create Custom Element Property Getters and Setters with&nbsp;MooTools</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/mootools-custom-element/feed</wfw:commentRss> <slash:comments>5</slash:comments> </item> <item><title>Create a Basic Web Service Using PHP, MySQL, XML, and&#160;JSON</title><link>http://davidwalsh.name/web-service-php-mysql-xml-json</link> <comments>http://davidwalsh.name/web-service-php-mysql-xml-json#comments</comments> <pubDate>Wed, 06 May 2009 12:36:25 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[APIs]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Markup]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=2324</guid> <description><![CDATA[Web services are taking over the world. I credit Twitter&#8217;s epic rise to the availability of a simple but rich API. Why not use the same model for your own sites? Here&#8217;s how to create a basic web service that provides an XML or JSON response using some PHP and MySQL. The PHP /&#160;MySQL /* [...]<p><a
href="http://davidwalsh.name/web-service-php-mysql-xml-json">Create a Basic Web Service Using PHP, MySQL, XML, and&nbsp;JSON</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p>Web services are taking over the world.  I credit Twitter&#8217;s epic rise to the availability of a simple but rich API.  Why not use the same model for your own sites?  Here&#8217;s how to create a basic web service that provides an XML or JSON response using some PHP and MySQL.</p><h2>The PHP /&nbsp;MySQL</h2><pre class="php">/* require the user as the parameter */
if(isset($_GET['user']) &#038;&#038; intval($_GET['user'])) {

	/* soak in the passed variable or set our own */
	$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
	$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
	$user_id = intval($_GET['user']); //no default

	/* connect to the db */
	$link = mysql_connect('localhost','username','password') or die('Cannot connect to the DB');
	mysql_select_db('db_name',$link) or die('Cannot select the DB');

	/* grab the posts from the db */
	$query = "SELECT post_title, guid FROM wp_posts WHERE post_author = $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
	$result = mysql_query($query,$link) or die('Errant query:  '.$query);

	/* create one master array of the records */
	$posts = array();
	if(mysql_num_rows($result)) {
		while($post = mysql_fetch_assoc($result)) {
			$posts[] = array('post'=&gt;$post);
		}
	}

	/* output in necessary format */
	if($format == 'json') {
		header('Content-type: application/json');
		echo json_encode(array('posts'=&gt;$posts));
	}
	else {
		header('Content-type: text/xml');
		echo '&lt;posts&gt;';
		foreach($posts as $index =&gt; $post) {
			if(is_array($post)) {
				foreach($post as $key =&gt; $value) {
					echo '&lt;',$key,'&gt;';
					if(is_array($value)) {
						foreach($value as $tag =&gt; $val) {
							echo '&lt;',$tag,'&gt;',htmlentities($val),'&lt;/',$tag,'&gt;';
						}
					}
					echo '&lt;/',$key,'&gt;';
				}
			}
		}
		echo '&lt;/posts&gt;';
	}

	/* disconnect from the db */
	@mysql_close($link);
}</pre><p>With the number of persons hitting your web service (hopefully), you&#8217;ll need to do adequate validation before attempting to connect to the database to avoid injection attacks.  Once we get the desired results from the database, we cycle through the results to populate our return results array.  Depending upon the response type desired, we output the proper header and content in the desired format.</p><p>Take the following sample URL for example:</p><pre class="html">http://mydomain.com/web-service.php?user=2&amp;num=10</pre><p>Now, we can take a look at the possible results of the URL.</p><h2>The XML&nbsp;Output</h2><pre class="xml">&lt;posts&gt;
	&lt;post&gt;
		&lt;post_title&gt;SSLmatic SSL Certificate Giveaway Winners&lt;/post_title&gt;
		&lt;guid&gt;http://davidwalsh.name/?p=2304&lt;/guid&gt;
	&lt;/post&gt;
	&lt;post&gt;
		&lt;post_title&gt;MooTools FileManager&lt;/post_title&gt;
		&lt;guid&gt;http://davidwalsh.name/?p=2288&lt;/guid&gt;
	&lt;/post&gt;
	&lt;post&gt;
		&lt;post_title&gt;PHPTVDB: Using PHP to Retrieve TV Show Information&lt;/post_title&gt;
		&lt;guid&gt;http://davidwalsh.name/?p=2266&lt;/guid&gt;
	&lt;/post&gt;
	&lt;post&gt;
		&lt;post_title&gt;David Walsh: The Lost MooTools Plugins&lt;/post_title&gt;
		&lt;guid&gt;http://davidwalsh.name/?p=2258&lt;/guid&gt;
	&lt;/post&gt;
	&lt;post&gt;
		&lt;post_title&gt;Create Short URLs Using U.Nu&lt;/post_title&gt;
		&lt;guid&gt;http://davidwalsh.name/?p=2218&lt;/guid&gt;
	&lt;/post&gt;
	&lt;post&gt;
		&lt;post_title&gt;Create Bit.ly Short URLs Using PHP&lt;/post_title&gt;
		&lt;guid&gt;http://davidwalsh.name/?p=2194&lt;/guid&gt;
	&lt;/post&gt;
	&lt;post&gt;
		&lt;post_title&gt;Represent Your Repositories Using the GitHub Badge!&lt;/post_title&gt;
		&lt;guid&gt;http://davidwalsh.name/?p=2178&lt;/guid&gt;
	&lt;/post&gt;
	&lt;post&gt;
		&lt;post_title&gt;ZebraTable&lt;/post_title&gt;
		&lt;guid&gt;http://davidwalsh.name/?page_id=2172&lt;/guid&gt;
	&lt;/post&gt;
	&lt;post&gt;
		&lt;post_title&gt;MooTools Zebra Table Plugin&lt;/post_title&gt;
		&lt;guid&gt;http://davidwalsh.name/?p=2168&lt;/guid&gt;
	&lt;/post&gt;
	&lt;post&gt;
		&lt;post_title&gt;SSLmatic: Quality, Cheap SSL Certificates and Giveaway!&lt;/post_title&gt;
		&lt;guid&gt;http://davidwalsh.name/?p=2158&lt;/guid&gt;
	&lt;/post&gt;
&lt;/posts&gt;</pre><p>Take this next sample URL for example:</p><pre class="html">http://mydomain.com/web-service.php?user=2&amp;num=10&amp;format=json</pre><p>Now, we can take a look at the possible results of the URL.</p><h2>The JSON&nbsp;Output</h2><pre class="js">{"posts":[{"post":{"post_title":"SSLmatic SSL Certificate Giveaway Winners","guid":"http:\/\/davidwalsh.name\/?p=2304"}},{"post":{"post_title":"MooTools FileManager","guid":"http:\/\/davidwalsh.name\/?p=2288"}},{"post":{"post_title":"PHPTVDB: Using PHP to Retrieve TV Show Information","guid":"http:\/\/davidwalsh.name\/?p=2266"}},{"post":{"post_title":"David Walsh: The Lost MooTools Plugins","guid":"http:\/\/davidwalsh.name\/?p=2258"}},{"post":{"post_title":"Create Short URLs Using U.Nu","guid":"http:\/\/davidwalsh.name\/?p=2218"}},{"post":{"post_title":"Create Bit.ly Short URLs Using PHP","guid":"http:\/\/davidwalsh.name\/?p=2194"}},{"post":{"post_title":"Represent Your Repositories Using the GitHub Badge!","guid":"http:\/\/davidwalsh.name\/?p=2178"}},{"post":{"post_title":"ZebraTable","guid":"http:\/\/davidwalsh.name\/?page_id=2172"}},{"post":{"post_title":"MooTools Zebra Table Plugin","guid":"http:\/\/davidwalsh.name\/?p=2168"}},{"post":{"post_title":"SSLmatic: Quality, Cheap SSL Certificates and Giveaway!","guid":"http:\/\/davidwalsh.name\/?p=2158"}}]}</pre><p>Creating a basic web service is very simple and encourages your users to spread the word about your website or service.  Want more traffic?  Want your website to grow without you putting in all the effort?  Create a web service!</p><p><a
href="http://davidwalsh.name/web-service-php-mysql-xml-json">Create a Basic Web Service Using PHP, MySQL, XML, and&nbsp;JSON</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/web-service-php-mysql-xml-json/feed</wfw:commentRss> <slash:comments>77</slash:comments> </item> <item><title>Backup Your Database into an XML File Using&#160;PHP</title><link>http://davidwalsh.name/backup-database-xml-php</link> <comments>http://davidwalsh.name/backup-database-xml-php#comments</comments> <pubDate>Fri, 27 Feb 2009 14:19:35 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[Markup]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=1409</guid> <description><![CDATA[Backing up data is extremely important. Most of the time the database is the most important piece of the puzzle. Imagine losing all of the data in your database &#8212; it would be tragic. Here&#8217;s a PHP snippet that outputs your database as XML. The&#160;PHP //connect $link = mysql_connect($host,$user,$pass); mysql_select_db($name,$link); //get all the tables $query [...]<p><a
href="http://davidwalsh.name/backup-database-xml-php">Backup Your Database into an XML File Using&nbsp;PHP</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p>Backing up data is extremely important.  Most of the time the database is the most important piece of the puzzle.  Imagine losing all of the data in your database &#8212; it would be tragic.  Here&#8217;s a PHP snippet that outputs your database as XML.</p><h2>The&nbsp;PHP</h2><pre class="php">
//connect
$link = mysql_connect($host,$user,$pass);
mysql_select_db($name,$link);

//get all the tables
$query = 'SHOW TABLES FROM '.$name;
$result = mysql_query($query,$link) or die('cannot show tables');
if(mysql_num_rows($result))
{
	//prep output
	$tab = "\t";
	$br = "\n";
	$xml = '&lt;?xml version="1.0" encoding="UTF-8"?&gt;'.$br;
	$xml.= '&lt;database name="'.$name.'"&gt;'.$br;
	
	//for every table...
	while($table = mysql_fetch_row($result))
	{
		//prep table out
		$xml.= $tab.'&lt;table name="'.$table[0].'"&gt;'.$br;
		
		//get the rows
		$query3 = 'SELECT * FROM '.$table[0];
		$records = mysql_query($query3,$link) or die('cannot select from table: '.$table[0]);
		
		//table attributes
		$attributes = array('name','blob','maxlength','multiple_key','not_null','numeric','primary_key','table','type','default','unique_key','unsigned','zerofill');
		$xml.= $tab.$tab.'&lt;columns&gt;'.$br;
		$x = 0;
		while($x &lt; mysql_num_fields($records))
		{
			$meta = mysql_fetch_field($records,$x);
			$xml.= $tab.$tab.$tab.'&lt;column ';
			foreach($attributes as $attribute)
			{
				$xml.= $attribute.'="'.$meta-&gt;$attribute.'" ';
			}
			$xml.= '/&gt;'.$br;
			$x++;
		}
		$xml.= $tab.$tab.'&lt;/columns&gt;'.$br;
		
		//stick the records
		$xml.= $tab.$tab.'&lt;records&gt;'.$br;
		while($record = mysql_fetch_assoc($records))
		{
			$xml.= $tab.$tab.$tab.'&lt;record&gt;'.$br;
			foreach($record as $key=&gt;$value)
			{
				$xml.= $tab.$tab.$tab.$tab.'&lt;'.$key.'&gt;'.htmlspecialchars(stripslashes($value)).'&lt;/'.$key.'&gt;'.$br;
			}
			$xml.= $tab.$tab.$tab.'&lt;/record&gt;'.$br;
		}
		$xml.= $tab.$tab.'&lt;/records&gt;'.$br;
		$xml.= $tab.'&lt;/table&gt;'.$br;
	}
	$xml.= '&lt;/database&gt;';
	
	//save file
	$handle = fopen($name.'-backup-'.time().'.xml','w+');
	fwrite($handle,$xml);
	fclose($handle);
}
</pre><p>You probably don&#8217;t NEED to add column nodes but I like including as much data as possible and they don&#8217;t add very much to the total file size.</p><h2>The Sample&nbsp;Output</h2><pre class="xml">
&lt;database name="my_database"&gt;
	&lt;table name="wp_comments"&gt;
		&lt;columns&gt;
			&lt;column name="comment_ID" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="1" primary_key="1" table="wp_comments" type="int" default="" unique_key="0" unsigned="1" zerofill="0" /&gt;
			&lt;column name="comment_post_ID" blob="0" maxlength="" multiple_key="1" not_null="1" numeric="1" primary_key="0" table="wp_comments" type="int" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="comment_author" blob="1" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_comments" type="blob" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="comment_author_email" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_comments" type="string" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="comment_author_url" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_comments" type="string" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="comment_author_IP" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_comments" type="string" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="comment_date" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_comments" type="datetime" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="comment_date_gmt" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_comments" type="datetime" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="comment_content" blob="1" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_comments" type="blob" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="comment_karma" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="1" primary_key="0" table="wp_comments" type="int" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="comment_approved" blob="0" maxlength="" multiple_key="1" not_null="1" numeric="0" primary_key="0" table="wp_comments" type="string" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="comment_agent" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_comments" type="string" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="comment_type" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_comments" type="string" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="comment_parent" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="1" primary_key="0" table="wp_comments" type="int" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="user_id" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="1" primary_key="0" table="wp_comments" type="int" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
		&lt;/columns&gt;
		&lt;records&gt;
			&lt;record&gt;
				&lt;comment_ID&gt;2&lt;/comment_ID&gt;
				&lt;comment_post_ID&gt;4&lt;/comment_post_ID&gt;
				&lt;comment_author&gt;Ryan&lt;/comment_author&gt;
				&lt;comment_author_email&gt;r&#121;an&#116;a&#115;tad&#64;ho&#116;&#109;&#97;i&#108;.&#99;om&lt;/comment_author_email&gt;
				&lt;comment_author_url&gt;&lt;/comment_author_url&gt;
				&lt;comment_author_IP&gt;66.84.199.242&lt;/comment_author_IP&gt;
				&lt;comment_date&gt;2007-12-06 10:10:38&lt;/comment_date&gt;
				&lt;comment_date_gmt&gt;2007-12-06 16:10:38&lt;/comment_date_gmt&gt;
				&lt;comment_content&gt;Roethlisberger is coming to town!?  Sorry, Fred.&lt;/comment_content&gt;
				&lt;comment_karma&gt;0&lt;/comment_karma&gt;
				&lt;comment_approved&gt;1&lt;/comment_approved&gt;
				&lt;comment_agent&gt;Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322)&lt;/comment_agent&gt;
				&lt;comment_type&gt;&lt;/comment_type&gt;
				&lt;comment_parent&gt;0&lt;/comment_parent&gt;
				&lt;user_id&gt;0&lt;/user_id&gt;
			&lt;/record&gt;
		&lt;/records&gt;
	&lt;/table&gt;
	&lt;table name="wp_links"&gt;
		&lt;columns&gt;
			&lt;column name="link_id" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="1" primary_key="1" table="wp_links" type="int" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="link_url" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_links" type="string" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="link_name" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_links" type="string" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="link_image" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_links" type="string" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="link_target" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_links" type="string" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="link_category" blob="0" maxlength="" multiple_key="1" not_null="1" numeric="1" primary_key="0" table="wp_links" type="int" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="link_description" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_links" type="string" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="link_visible" blob="0" maxlength="" multiple_key="1" not_null="1" numeric="0" primary_key="0" table="wp_links" type="string" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="link_owner" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="1" primary_key="0" table="wp_links" type="int" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="link_rating" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="1" primary_key="0" table="wp_links" type="int" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="link_updated" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_links" type="datetime" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="link_rel" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_links" type="string" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="link_notes" blob="1" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_links" type="blob" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
			&lt;column name="link_rss" blob="0" maxlength="" multiple_key="0" not_null="1" numeric="0" primary_key="0" table="wp_links" type="string" default="" unique_key="0" unsigned="0" zerofill="0" /&gt;
		&lt;/columns&gt;
		&lt;records&gt;
			&lt;record&gt;
				&lt;link_id&gt;1&lt;/link_id&gt;
				&lt;link_url&gt;http://codex.wordpress.org/&lt;/link_url&gt;
				&lt;link_name&gt;Documentation&lt;/link_name&gt;
				&lt;link_image&gt;&lt;/link_image&gt;
				&lt;link_target&gt;&lt;/link_target&gt;
				&lt;link_category&gt;0&lt;/link_category&gt;
				&lt;link_description&gt;&lt;/link_description&gt;
				&lt;link_visible&gt;Y&lt;/link_visible&gt;
				&lt;link_owner&gt;1&lt;/link_owner&gt;
				&lt;link_rating&gt;0&lt;/link_rating&gt;
				&lt;link_updated&gt;0000-00-00 00:00:00&lt;/link_updated&gt;
				&lt;link_rel&gt;&lt;/link_rel&gt;
				&lt;link_notes&gt;&lt;/link_notes&gt;
				&lt;link_rss&gt;&lt;/link_rss&gt;
			&lt;/record&gt;
			&lt;record&gt;
				&lt;link_id&gt;2&lt;/link_id&gt;
				&lt;link_url&gt;http://wordpress.org/development/&lt;/link_url&gt;
				&lt;link_name&gt;Development Blog&lt;/link_name&gt;
				&lt;link_image&gt;&lt;/link_image&gt;
				&lt;link_target&gt;&lt;/link_target&gt;
				&lt;link_category&gt;0&lt;/link_category&gt;
				&lt;link_description&gt;&lt;/link_description&gt;
				&lt;link_visible&gt;Y&lt;/link_visible&gt;
				&lt;link_owner&gt;1&lt;/link_owner&gt;
				&lt;link_rating&gt;0&lt;/link_rating&gt;
				&lt;link_updated&gt;0000-00-00 00:00:00&lt;/link_updated&gt;
				&lt;link_rel&gt;&lt;/link_rel&gt;
				&lt;link_notes&gt;&lt;/link_notes&gt;
				&lt;link_rss&gt;http://wordpress.org/development/feed/&lt;/link_rss&gt;
			&lt;/record&gt;
		&lt;/records&gt;
	&lt;/table&gt;
&lt;/database&gt;
</pre><p>XML isn&#8217;t the easiest format to restore a table with so you may prefer to <a
href="http://davidwalsh.name/backup-mysql-database-php">export the table as SQL statements</a>.  I enjoy the additional XML backup because it&#8217;s easy to read.</p><p><a
href="http://davidwalsh.name/backup-database-xml-php">Backup Your Database into an XML File Using&nbsp;PHP</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/backup-database-xml-php/feed</wfw:commentRss> <slash:comments>20</slash:comments> </item> <item><title>Animated AJAX Record Deletion Using&#160;MooTools</title><link>http://davidwalsh.name/animated-ajax-record-deletion-mootools</link> <comments>http://davidwalsh.name/animated-ajax-record-deletion-mootools#comments</comments> <pubDate>Thu, 29 Jan 2009 13:54:51 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[MooTools]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=1289</guid> <description><![CDATA[I&#8217;m a huge fan of WordPress&#8217; method of individual article deletion. You click the delete link, the menu item animates red, and the item disappears. Here&#8217;s how to achieve that functionality with MooTools JavaScript. View Demo The PHP &#8211; Content &#38;&#160;Header The following snippet goes at the top of the page: if(isset($_GET['delete'])) { $query = [...]<p><a
href="http://davidwalsh.name/animated-ajax-record-deletion-mootools">Animated AJAX Record Deletion Using&nbsp;MooTools</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p>I&#8217;m a huge fan of WordPress&#8217; method of individual article deletion.  You click the delete link, the menu item animates red, and the item disappears.  Here&#8217;s how to achieve that functionality with MooTools JavaScript.</p><div
class="actions"> <a
href="http://davidwalsh.name/dw-content/mootools-record-delete.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>The PHP &#8211; Content &amp;&nbsp;Header</h2><p>The following snippet goes at the top of the page:</p><pre class="php">
if(isset($_GET['delete']))
{
	$query = 'DELETE FROM my_table WHERE item_id = '.(int)$_GET['delete'];
	$result = mysql_query($query,$link);
}
</pre><p>The following is used to display the records:</p><pre class="php">
$query = 'SELECT * FROM my_table ORDER BY title ASC';
$result = mysql_query($query,$link);
while($row = mysql_fetch_assoc($result))
{
	echo '&lt;div class="record" id="record-',$row['item_id'],'"&gt;
				&lt;a href="?delete=',$row['item_id'],'" class="delete"&gt;Delete&lt;/a&gt;
				&lt;strong&gt;',$row['title'],'&lt;/strong&gt;
			&lt;/div&gt;';
}
</pre><h2>The MooTools&nbsp;JavaScript</h2><pre class="js">
window.addEvent('domready',function() {
	$$('a.delete').each(function(el) {
		el.addEvent('click',function(e) {
			e.stop();
			var parent = el.getParent('div');
			var request = new Request({
				url: 'mootools-record-delete.php',
				link: 'chain',
				method: 'get',
				data: {
					'delete': parent.get('id').replace('record-',''),
					ajax: 1
				},
				onRequest: function() {
					new Fx.Tween(parent,{
						duration:300
					}).start('background-color', '#fb6c6c');
				},
				onSuccess: function() {
					new Fx.Slide(parent,{
						duration:300,
						onComplete: function() {
							parent.dispose();
						}
					}).slideOut();
				}
			}).send();
		});
	});
});
</pre><p>For every link, we add a click event that triggers the AJAX request.  During the request, we tween the containing element to a red background.  When the AJAX request returns a &#8220;success&#8221; response, we slide the element off of the screen.</p><div
class="actions"> <a
href="http://davidwalsh.name/dw-content/mootools-record-delete.php" class="demo">View Demo</a><div
class="clear"></div></div><p>How would you use this?  Share!</p><p><a
href="http://davidwalsh.name/animated-ajax-record-deletion-mootools">Animated AJAX Record Deletion Using&nbsp;MooTools</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/animated-ajax-record-deletion-mootools/feed</wfw:commentRss> <slash:comments>49</slash:comments> </item> <item><title>Breaking &amp; Fixing Dates from MySQL to&#160;PHP</title><link>http://davidwalsh.name/dates-mysql-php</link> <comments>http://davidwalsh.name/dates-mysql-php#comments</comments> <pubDate>Wed, 19 Nov 2008 12:05:55 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=776</guid> <description><![CDATA[The way that databases store &#8220;date&#8221; field data is: 2008-11-19 // year - month - day The way that us humans read dates (at least in the U.S.) is: 11-19-2008 // month - day - year I write a lot of administrative panel modules that either display dates or, better yet, allow customers to their [...]<p><a
href="http://davidwalsh.name/dates-mysql-php">Breaking &#038; Fixing Dates from MySQL to&nbsp;PHP</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p>The way that databases store &#8220;date&#8221; field data is:</p><pre  class="js">
2008-11-19 // year - month - day
</pre><p>The way that us humans read dates (at least in the U.S.) is:</p><pre  class="js">
11-19-2008 // month - day - year
</pre><p>I write a lot of administrative panel modules that either display dates or, better yet, allow customers to their own dates for articles, events, etc.  I&#8217;ve created a couple of PHP functions that allow me to easily handle the transition from MySQL to PHP and visa versa.</p><h2>The PHP:  MySQL to&nbsp;PHP</h2><pre  class="php">
	/* break a date */
	function break_date($date)
	{
		$date = explode('-',str_replace('/','-',$date)); 
		return $date[1].'-'.$date[2].'-'.$date[0];
	}
</pre><h2>The PHP:  PHP to&nbsp;MySQL</h2><pre  class="php">
	/* fix a date */
	function fix_date($date)
	{
		$date = explode('-',str_replace('/','-',$date)); 
		return $date[2].'-'.$date[0].'-'.$date[1];
	}
</pre><p>You&#8217;ll see that I automatically replace &#8220;/&#8221; within the given date, break apart the date string, and rearrange the items to make the user and the database happy.  Hopefully this saves someone some time!</p><p><a
href="http://davidwalsh.name/dates-mysql-php">Breaking &#038; Fixing Dates from MySQL to&nbsp;PHP</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/dates-mysql-php/feed</wfw:commentRss> <slash:comments>36</slash:comments> </item> <item><title>Using MooTools 1.2 For Drag, Drop, Sort,&#160;Save</title><link>http://davidwalsh.name/mootools-drag-drop</link> <comments>http://davidwalsh.name/mootools-drag-drop#comments</comments> <pubDate>Fri, 14 Nov 2008 13:57:36 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[CSS]]></category> <category><![CDATA[Markup]]></category> <category><![CDATA[MooTools]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=328</guid> <description><![CDATA[This post has been updated: Using jQuery or MooTools For Drag, Drop, Sort, Save. The code on this page is no longer best practice. The following is a repost of an article that ran on Script &#038; Style a few months ago&#8230;. My customers love being able to control their website&#8217;s content so I build [...]<p><a
href="http://davidwalsh.name/mootools-drag-drop">Using MooTools 1.2 For Drag, Drop, Sort,&nbsp;Save</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p
class="post-updated">This post has been updated: <a
href="http://davidwalsh.name/mootools-drag-ajax">Using jQuery or MooTools For Drag, Drop, Sort, Save</a>.  The code on this page is no longer best practice.</p><p><em>The following is a repost of an article that ran on <a
href="http://scriptandstyle.com">Script &#038; Style</a> a few months ago&#8230;.</em></p><p> <a
href="http://davidwalsh.name/dw-content/sort-save.php"><img
class="image" src="http://davidwalsh.name/dw-content/sort-save.jpg" alt="" /></a> My customers love being able to control their website&#8217;s content so I build a lot of administrative control into their website.  One administrative control I frequently build is a News control.  I allow the customer to add, edit, delete, and sort news items.  My customers especially love sorting their articles because of the fashion of which they can sort:  drag and drop.   Here&#8217;s how I do it.</p><div
class="actions"> <a
href="http://davidwalsh.name/dw-content/sort-save.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>The MySQL&nbsp;Table</h2><table
border="0" cellspacing="0" cellpadding="0" class="poll-results"><tr><th>id</th><th>title</th><th>sort_order</th></tr><tr><td>1</td><td>Article 1</td><td>1</td></tr><tr><td>2</td><td>Article 2</td><td>2</td></tr><tr><td>3</td><td>Article 3</td><td>3</td></tr><tr><td>4</td><td>Article 4</td><td>4</td></tr><tr><td>5</td><td>Article 5</td><td>5</td></tr><tr><td>6</td><td>Article 6</td><td>6</td></tr></table><p>My news table contains more fields but these are the important fields per this example.</p><h2>The PHP /&nbsp;XHTML</h2><pre  class="php">&lt;?php
&lt;div id="message-box"&gt;&lt;?php echo $message; ?&gt; Waiting for sortation submission...&lt;/div&gt;

&lt;form id="dd-form" action="&lt;?php echo $_SERVER['REQUEST_URI']; ?&gt;" method="post"&gt;
&lt;p&gt;&lt;input type="checkbox" value="1" name="auto_submit" id="auto_submit" &lt;?php if($_POST['auto_submit']) { echo 'checked="checked"'; } ?&gt; /&gt; &lt;label for="auto_submit"&gt;Automatically submit on drop event&lt;/label&gt;&lt;/p&gt;

&lt;ul id="sortable-list"&gt;
	&lt;?php 
		$sort_order = array();
		while($item = mysql_fetch_assoc($result))
		{
			echo '&lt;li class="sortme" alt="',$item['id'],'"&gt;',$item['title'],'&lt;/li&gt;';
			$sort_order[] = $item['sort_order'];
		}
	?&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;input type="hidden" name="sort_order" id="sort_order" value="&lt;?php echo implode($sort_order,'|'); ?&gt;" /&gt;
&lt;input type="submit" name="do_submit" value="Submit Sortation" class="button" /&gt;
&lt;/form&gt;
&lt;?php } else { ?&gt;
	
	&lt;p&gt;Sorry!  There are no items in the system.&lt;/p&gt;
	
&lt;?php } ?&gt;
</pre><p>We query the database to get every news item.  What&#8217;s extremely important is that the query sorts the items by their original sort order.  We set the &#8220;rel&#8221; attribute equal to the article&#8217;s ID and the list item&#8217;s text to the article title.</p><h2>The&nbsp;CSS</h2><pre  class="css">#sortable-list				{ padding:0; }
li.sortme 		 			{ padding:4px 8px; color:#000; cursor:move; list-style:none; width:500px; background:#ddd; margin:10px 0; border:1px solid #999; }
#message-box				{ background:#fffea1; border:2px solid #fc0; padding:4px 8px; margin:0 0 14px 0; width:500px; }
</pre><p> I use the above CSS to format the news items so that the customer knows each news item may be dragged.  None of the CSS is essential to this system.</p><h2>The MooTools&nbsp;JavaScript</h2><pre  class="js">/* when the DOM is ready */
/* create sortables */
	var sb = new Sortables('sortable-list', {
		/* set options */
		clone:true,
		revert: true,
		/* initialization stuff here */
		initialize: function() { 
			
		},
		/* once an item is selected */
		onStart: function(el) { 
			el.setStyle('background','#add8e6');
		},
		/* when a drag is complete */
		onComplete: function(el) {
			el.setStyle('background','#ddd');
			//build a string of the order
			var sort_order = '';
			$$('#sortable-list li').each(function(li) { sort_order = sort_order +  li.get('alt')  + '|'; });
			$('sort_order').value = sort_order;
			
			//autosubmit if the checkbox says to
			if($('auto_submit').checked) {
				//do an ajax request
				var req = new Request({
					url:'<?php echo $_SERVER['PHP_SELF']; ?>',
					method:'post',
					autoCancel:true,
					data:'sort_order=' + sort_order + '&#038;ajax=' + $('auto_submit').checked + '&#038;do_submit=1&#038;byajax=1',
					onRequest: function() {
						$('message-box').set('text','Updating the sort order in the database.');
					},
					onSuccess: function() {
						$('message-box').set('text','Database has been updated.');
					}
				}).send();
			}
		}
	});
});
</pre><p>We use Moo 1.2&#8242;s Sortables plugin class to select all element within the list and make them sortable (drag and drop).  Every time the sort order is changed, the hidden <span
class="parameter">sort_order</span> element is built and reset using a &#8220;|&#8221; as a separator.  If the checkbox is checked, an ajax call is made to update the sort order in the database.  Otherwise, the regular form submission via submit button will also save the sortation.</p><h2>The &#8220;Header&#8221; PHP /&nbsp;MySQL</h2><pre  class="php">/* on form submission */
if(isset($_POST['do_submit'])) 
{
	/* split the value of the sortation */
	$ids = explode('|',$_POST['sort_order']);
	
	/* run the update query for each id */
	foreach($ids as $index=>$id)
	{
		if($id != '')
		{
			$query = 'UPDATE test_table SET sort_order = '.$index.' WHERE id = '.$id;
			$result = mysql_query($query,$connection) or die(mysql_error().': '.$query);
		}
	}
	
	/* now what? */
	if($_POST['byajax']) { die(); } else { $message = 'Sortation has been saved.'; }
}
</pre><div
class="actions"> <a
href="http://davidwalsh.name/dw-content/sort-save.php" class="demo">View Demo</a><div
class="clear"></div></div><p>The header is where the new sort order is committed.  We split the <span
class="param">sort_order</span> form value by the &#8220;|&#8221; and perform a query for each item to update its order.  Lastly, if the <span
class="param">byajax</span> flag is sent, we just die out the PHP script &#8212; if not, we continue to load the page.</p><p>Hot system, right? Dragging and dropping is by far the fastest way to sort a list of items.  What are your thoughts?  Have any ideas for improvements?</p><p><a
href="http://davidwalsh.name/mootools-drag-drop">Using MooTools 1.2 For Drag, Drop, Sort,&nbsp;Save</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/mootools-drag-drop/feed</wfw:commentRss> <slash:comments>70</slash:comments> </item> <item><title>Format Date Fields Using MySQL&#160;DATE_FORMAT()</title><link>http://davidwalsh.name/format-date-mysql-date_format</link> <comments>http://davidwalsh.name/format-date-mysql-date_format#comments</comments> <pubDate>Fri, 03 Oct 2008 12:51:01 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[MySQL]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=410</guid> <description><![CDATA[I use MySQL DATE and DATETIME fields almost as much as VARCHAR fields. I use them mostly to track record creation, record updates, and record expiration dates. The default date format in MYSQL is: 2008-09-10 22:50:02 When I pull this information into the page, I want to show the date in human-readable format. That&#8217;s where [...]<p><a
href="http://davidwalsh.name/format-date-mysql-date_format">Format Date Fields Using MySQL&nbsp;DATE_FORMAT()</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p>I use MySQL <span
class="param">DATE</span> and <span
class="param">DATETIME</span> fields almost as much as <span
class="param">VARCHAR</span> fields.  I use them mostly to track record creation, record updates, and record expiration dates.  The default date format in MYSQL is:</p><pre  class="sql">
2008-09-10 22:50:02
</pre><p>When I pull this information into the page, I want to show the date in human-readable format.  That&#8217;s where MySQL&#8217;s <span
class="param">DATE_FORMAT</span> functionality comes in. <span
class="param">DATE_FORMAT</span> allows me to format the date in any manner you&#8217;d like.</p><h2>MySQL DATE_FORMAT()&nbsp;Example</h2><pre  class="sql">
DATE_FORMAT(NOW(),'%W, %M %e, %Y @ %h:%i %p')
#yields 'Sunday, September 20, 2008 @ 12:45 PM'
</pre><h2>MySQL DATE_FORMAT() Letter&nbsp;Representations</h2><table
cellpadding="0" cellspacing="0" class="poll-results"><tr><th><span
class="bold"><strong>Specifier</strong></span></th><th><span
class="bold"><strong>Description</strong></span></th></tr><tr><td><code
class="literal"><b>%a</b></code></td><td>Abbreviated weekday name
(<code
class="literal">Sun</code>..<code
class="literal">Sat</code>)</td></tr><tr><td><code
class="literal"><b>%b</b></code></td><td>Abbreviated month name (<code
class="literal">Jan</code>..<code
class="literal">Dec</code>)</td></tr><tr><td><code
class="literal"><b>%c</b></code></td><td>Month, numeric (<code
class="literal">0</code>..<code
class="literal">12</code>)</td></tr><tr><td><code
class="literal"><b>%D</b></code></td><td>Day of the month with English suffix (<code
class="literal">0th</code>, <code
class="literal">1st</code>, <code
class="literal">2nd</code>, <code
class="literal">3rd</code>, …)</td></tr><tr><td><code
class="literal"><b>%d</b></code></td><td>Day of the month, numeric (<code
class="literal">00</code>..<code
class="literal">31</code>)</td></tr><tr><td><code
class="literal"><b>%e</b></code></td><td>Day of the month, numeric (<code
class="literal">0</code>..<code
class="literal">31</code>)</td></tr><tr><td><code
class="literal"><b>%f</b></code></td><td>Microseconds (<code
class="literal">000000</code>..<code
class="literal">999999</code>)</td></tr><tr><td><code
class="literal"><b>%H</b></code></td><td>Hour (<code
class="literal">00</code>..<code
class="literal">23</code>)</td></tr><tr><td><code
class="literal"><b>%h</b></code></td><td>Hour (<code
class="literal">01</code>..<code
class="literal">12</code>)</td></tr><tr><td><code
class="literal"><b>%I</b></code></td><td>Hour (<code
class="literal">01</code>..<code
class="literal">12</code>)</td></tr><tr><td><code
class="literal"><b>%i</b></code></td><td>Minutes, numeric (<code
class="literal">00</code>..<code
class="literal">59</code>)</td></tr><tr><td><code
class="literal"><b>%j</b></code></td><td>Day of year (<code
class="literal">001</code>..<code
class="literal">366</code>)</td></tr><tr><td><code
class="literal"><b>%k</b></code></td><td>Hour (<code
class="literal">0</code>..<code
class="literal">23</code>)</td></tr><tr><td><code
class="literal"><b>%l</b></code></td><td>Hour (<code
class="literal">1</code>..<code
class="literal">12</code>)</td></tr><tr><td><code
class="literal"><b>%M</b></code></td><td>Month name (<code
class="literal">January</code>..<code
class="literal">December</code>)</td></tr><tr><td><code
class="literal"><b>%m</b></code></td><td>Month, numeric (<code
class="literal">00</code>..<code
class="literal">12</code>)</td></tr><tr><td><code
class="literal"><b>%p</b></code></td><td> <code
class="literal">AM</code> or <code
class="literal">PM</code></td></tr><tr><td><code
class="literal"><b>%r</b></code></td><td>Time, 12-hour (<code
class="literal">hh:mm:ss</code> followed by <code
class="literal">AM</code> or <code
class="literal">PM</code>)</td></tr><tr><td><code
class="literal"><b>%S</b></code></td><td>Seconds (<code
class="literal">00</code>..<code
class="literal">59</code>)</td></tr><tr><td><code
class="literal"><b>%s</b></code></td><td>Seconds (<code
class="literal">00</code>..<code
class="literal">59</code>)</td></tr><tr><td><code
class="literal"><b>%T</b></code></td><td>Time, 24-hour (<code
class="literal">hh:mm:ss</code>)</td></tr><tr><td><code
class="literal"><b>%U</b></code></td><td>Week (<code
class="literal">00</code>..<code
class="literal">53</code>), where Sunday is the
first day of the week</td></tr><tr><td><code
class="literal"><b>%u</b></code></td><td>Week (<code
class="literal">00</code>..<code
class="literal">53</code>), where Monday is the
first day of the week</td></tr><tr><td><code
class="literal"><b>%V</b></code></td><td>Week (<code
class="literal">01</code>..<code
class="literal">53</code>), where Sunday is the
first day of the week; used with <code
class="literal">%X</code></td></tr><tr><td><code
class="literal"><b>%v</b></code></td><td>Week (<code
class="literal">01</code>..<code
class="literal">53</code>), where Monday is the
first day of the week; used with <code
class="literal">%x</code></td></tr><tr><td><code
class="literal"><b>%W</b></code></td><td>Weekday name (<code
class="literal">Sunday</code>..<code
class="literal">Saturday</code>)</td></tr><tr><td><code
class="literal"><b>%w</b></code></td><td>Day of the week
(<code
class="literal">0</code>=Sunday..<code
class="literal">6</code>=Saturday)</td></tr><tr><td><code
class="literal"><b>%X</b></code></td><td>Year for the week where Sunday is the first day of the week, numeric,
four digits; used with <code
class="literal">%V</code></td></tr><tr><td><code
class="literal"><b>%x</b></code></td><td>Year for the week, where Monday is the first day of the week, numeric,
four digits; used with <code
class="literal">%v</code></td></tr><tr><td><code
class="literal"><b>%Y</b></code></td><td>Year, numeric, four digits</td></tr><tr><td><code
class="literal"><b>%y</b></code></td><td>Year, numeric (two digits)</td></tr><tr><td><code
class="literal"><b>%%</b></code></td><td>A literal “<span
class="quote"><code
class="literal">%</code></span>” character</td></tr><tr><td><code
class="literal"><b>%<em
class="replaceable"><code>x</code></em></b></code></td><td> <em
class="replaceable"><code>x</code></em>, for any
“<span
class="quote"><em
class="replaceable"><code>x</code></em></span>” not listed
above</td></tr></table><p>Be kind to your users and format the date for them!</p><p><a
href="http://davidwalsh.name/format-date-mysql-date_format">Format Date Fields Using MySQL&nbsp;DATE_FORMAT()</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/format-date-mysql-date_format/feed</wfw:commentRss> <slash:comments>24</slash:comments> </item> <item><title>Backup Your MySQL Database Using&#160;PHP</title><link>http://davidwalsh.name/backup-mysql-database-php</link> <comments>http://davidwalsh.name/backup-mysql-database-php#comments</comments> <pubDate>Mon, 18 Aug 2008 13:26:14 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=336</guid> <description><![CDATA[One of the most important tasks any developer needs to do often is back up their MySQL database. In many cases, the database is what drives most of the site. While most web hosts do a daily backup of a customer&#8217;s database, relying on them to make backups and provide them at no cost is [...]<p><a
href="http://davidwalsh.name/backup-mysql-database-php">Backup Your MySQL Database Using&nbsp;PHP</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p>One of the most important tasks any developer needs to do often is back up their MySQL database.  In many cases, the database is what drives most of the site.  While most web hosts do a daily backup of a customer&#8217;s database, relying on them to make backups and provide them at no cost is risky to say the least.  That&#8217;s why I&#8217;ve created a database backup function that I can call whenever I want &#8212; including nightly CRONs.</p><h2>The PHP &amp; MySQL&nbsp;Code</h2><pre  class="php">
backup_tables('localhost','username','password','blog');


/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
	
	$link = mysql_connect($host,$user,$pass);
	mysql_select_db($name,$link);
	
	//get all of the tables
	if($tables == '*')
	{
		$tables = array();
		$result = mysql_query('SHOW TABLES');
		while($row = mysql_fetch_row($result))
		{
			$tables[] = $row[0];
		}
	}
	else
	{
		$tables = is_array($tables) ? $tables : explode(',',$tables);
	}
	
	//cycle through
	foreach($tables as $table)
	{
		$result = mysql_query('SELECT * FROM '.$table);
		$num_fields = mysql_num_fields($result);
		
		$return.= 'DROP TABLE '.$table.';';
		$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
		$return.= "\n\n".$row2[1].";\n\n";
		
		for ($i = 0; $i < $num_fields; $i++) 
		{
			while($row = mysql_fetch_row($result))
			{
				$return.= 'INSERT INTO '.$table.' VALUES(';
				for($j=0; $j<$num_fields; $j++) 
				{
					$row[$j] = addslashes($row[$j]);
					$row[$j] = ereg_replace("\n","\\n",$row[$j]);
					if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
					if ($j<($num_fields-1)) { $return.= ','; }
				}
				$return.= ");\n";
			}
		}
		$return.="\n\n\n";
	}
	
	//save file
	$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
	fwrite($handle,$return);
	fclose($handle);
}
</pre><p>Of course, you'll need to provide database credentials to the function, as well as an array of tables you'd like to backup.  If you provide a "*" or no tables, a complete database backup will run.  The script does the rest!</p><p>Never take chances when your website is on the line.  Make frequent backups or pay the price later!</p><p><a
href="http://davidwalsh.name/backup-mysql-database-php">Backup Your MySQL Database Using&nbsp;PHP</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/backup-mysql-database-php/feed</wfw:commentRss> <slash:comments>208</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced (User agent is rejected)
Database Caching 1/65 queries in 0.018 seconds using disk: basic
Object Caching 1458/1565 objects using disk: basic

Served from: davidwalsh.name @ 2012-05-23 23:18:12 -->
