Archive for October, 2009
Detect if a Date is a Holiday (Portuguese example)
Saturday, October 31st, 2009
Detect whether a a specific date is a holiday. rss, snippets
Snippets | No Comments »
MB CopyMCF-DIR :: Copying or Moving Files and Child Files from Source Dir to Destination Dir
Saturday, October 31st, 2009
Copying or Moving Files and Child Files from Source Dir to Destination Dir rss, snippets
Snippets | No Comments »
Win the New Apple Magic Mouse
Saturday, October 31st, 2009
Across all of the TUTS sites, we’re starting a new weekly giveaway! This means that you should check Nettuts+ every Friday to potentially win a prize related to web development: anything from a new book, to a code editor, to Apple’s new magic mouse – which we’re giving away today!
Update: Winner Announced
Congratulations to Jason Wendell for being randomly chosen as the winner! Comments have now been closed.
“With Magic Mouse, Apple has brought Multi-Touch technology to the desktop mouse, giving you a new and more intuitive way to interact with your computer. Just as with iPhone, iPod touch, and MacBook Pro, the Bluetooth Magic Mouse adds gestures and swipes to the usual clicks to bring more functionality and help you get more done with less effort.” – via Amazon
How to Enter
Quite easily; simply make a tweet linking to your favorite tutorial on web development, whether it be from Nettuts+ or any other site. At the end of your link, add the #nettuts hash so that we can track it. Then, on Monday, November 2nd (US Central Time), I’ll sort through the tweets and select the winner! Anyone in the world, other than staff members, are eligible to enter!
Note: Envato staff and those who have written more than two articles for Nettuts+ are ineligible to enter.
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for the best web development tutorials on the web.
learn, php, rss, tutorials
PHP Tutorials | No Comments »
MySQLi access
Saturday, October 31st, 2009
The main class extends the MySQLi class : establish connection, execute SELECT, INSERT, UPDATE and DELETE queries from lists of parameters and get the fields of a table.
Exceptions of the class are handled by MySQLi_exception_class which extends the class Exception.
Other auxiliary classes deal with query results and prepare query statements.
classes, rss
Classes | No Comments »
Upcoming Bug Hunts!
Saturday, October 31st, 2009
As we near completion of the 2.9 milestone, it’s that time of dev cycle again, when we ask all you community developers who’ve been putting off contributing to core to dust off your dev environments and help us get closer to being release-ready. How? Bug hunts! Yes, that time-honored tradition (in the time of WordPress, anyway) of everyone pitching in to test patches and report the results, working on solutions to major bugs, and helping to clear out Trac has come around again, and we’re scheduling not one, but two bug hunts over the next couple of weeks to ensure that everyone has enough time to prepare and participate.
#1 – The first bug hunt of 2.9 will be Thursday through Saturday, November 5-7, 2009. This should give people a few days to plan for it, upgrade their dev environments if they haven’t been following trunk, and figure out how to allot their time. We’re stretching over both weekdays and weekend to try and accommodate everyone’s schedule.
#2 - The second bug hunt will be a week later, Saturday through Monday, November 14-16, 2009. This should make it possible for anyone who needs more than a week to set some time aside to participate. This bug hunt will coincide with WordCamp NYC, where a special Hacker Room will be set aside for people to go and work on 2.9 bug tickets alongside regular core contributors including Mark Jaquith and Matt Martz (sivel from IRC).
The Goals
Test, test, test existing patches! You can see all tickets with patches that need testing by checking this report. When you’ve tested a patch, report your results in the ticket comments, so core committers can see how the patch is faring.
Fix known bugs! You can see the bugs that need patches by checking this report. Look for the ones that seem that they’ll affect the most people or have the biggest impact by being fixed. Edge case bugs should be lower priority.
Report new bugs! As you’re testing out the development version, if you come across a bug, search trac to see if someone has reported it yet. If so, add a comment with your experience to the ticket so we’ll know it’s affecting more than one person. If no ticket exists yet, create one.
Core committers will be around (in the #wordpress-dev channel at irc.freenode.com) both weekends to review patches that have been thoroughly tested, answer questions as needed, and give feedback on patches that need more work before being commit-worthy.
If you’ve never participated in a WordPress bug hunt before, but you’d like to get involved, we’d love to have you join us! To prepare, you’ll want to set up a test environment, start using the current development version/maybe install the beta testing plugin, join us in the #wordpress-dev IRC channel, and read up on automated testing.
rss
Uncategorized | No Comments »
Simple XML Generator
Friday, October 30th, 2009
The generated document and be displayed as the current script output.
It takes an associative array and traverses it recursively to add tags and data to the XML document.
The code and comments are in Portuguese.
In Portuguese:
Simples classe que gera um arquivo XML a partir de um Array Associativo
classes, rss
Classes | No Comments »
How to Build a Simple Content Slider jQuery Plugin
Friday, October 30th, 2009
I was recently asked by a reader to recommend a helpful content slider plugin. No doubt, there are a bunch of excellent options available — some which are, perhaps, too excellent! With so much flexibility comes extra weight; especially when sometimes you only need a simple slide or fade transition.
So I figured, why not build a simple custom plugin that will get the job done?
Other Viewing Options
P.S. Speed Up
Don’t forget to take advantage of bundles when working in Textmate. If you need a helpful snippet to jump-start every new jQuery plugin, create a new snippet in Textmate, paste the following code in, and then assign a short-cut – like “jqueryplugin.”
(function(\$) {
\$.fn.$1 = function(options) {
var defaults = {
$2
},
options = \$.extend(defaults, options);
this.each(function() {
var \$this = \$(this);
$3
return this;
}); // end each
}
})(jQuery);
Conclusion
This is the only the first step. In the next screencast, we’ll continue refining this plugin, and adding more options/conveniences.
Thank you, Screencast.com!
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for the best web development tutorials on the web.
learn, php, rss, tutorials
PHP Tutorials | No Comments »
Executing multiple SQL statements stored in files
Thursday, October 29th, 2009
It can scan a given directory to retrieve the list of files it contains.
The class can read the file contents an execute the SQL statements contain in each line of the files.
classes, rss
Classes | No Comments »
Executing multipple SQL statements stored in files
Thursday, October 29th, 2009
It can scan a given directory to retrieve the list of files it contains.
The class can read the file contents an execute the SQL statements contain in each line of the files.
classes, rss
Classes | No Comments »
Simple Draggable Element Persistence with jQuery
Thursday, October 29th, 2009
At some point you may need to create a draggable element within your web application. This is great functionality, however you may want or find that you need the element to stay in place after being dragged around. In this tutorial I will show you how to easily drag an element and make it stick, even after a page reload, by grabbing and storing its X and Y coordinates.
Scenario
So you have an element in your web application. You can drag it around, put it here and put it there. But, when the page is reloaded in any way, the element returns to its default position. While you want the element to be draggable, you don’t want it to move after its been dragged. Let’s look at a simple solution to give us this ability.
Getting Started
For this tutorial we are going to need the jQuery library, jQuery UI, and the jQuery-JSON plugin by Brantley Harris. We will also be using some PHP and a MySQL database to parse and store our data. If your new to jQuery, no worries. jQuery is a highly extensible, fast, and lightweight JavaScript library which is both fun and easy to use. The library has very nicely structured documentation, and a huge community. This is my first tutorial on jQuery and JavaScript, so please bear with me. I hope to explain everything as best as I can and if you have any questions, please feel free to ask.

The HTML amd CSS
I wanted to start off with the HTML and styling for this tutorial since the effect is applyed to HTML elements, it helps to visualize what we are going to do, right off the bat. First the CSS:
html, body {
background:#151515;
margin:0 0 0 0;
padding:0 0 0 0;
}
#glassbox {
background:#333;
border:1px solid #000;
height:400px;
margin:30px auto auto auto;
position:relative;
width:960px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
}
#element {
background:#666;
border:1px #000 solid;
cursor:move;
height:143px;
padding:10px 10px 10px 10px;
width:202px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
}
#respond{
color:#fff;
margin:0 auto 0 auto;
width:960px;
}
The CSS is very simple. We set the html and body properties to clear margins and padding, and continue by setting some heights, widths, and other properties to our elements so it doesn’t look so bland. -moz-border-radius and -webkit-border-radius are two properties which allow us to create rounded borders (applicable only to Mozilla Firefox and Safari 3 at the moment) for our elements. Let’s take a look at the HTML:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Simple Draggable Element Persistence with jQuery</title> <link rel="stylesheet" href="style.css" type="text/css" /> <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script> <script type="text/javascript" src="js/jquery.json-2.2.min.js"></script> </head> <body> <div id="glassbox"> <div id="element"><img src="nettuts.jpg" alt="Nettuts+" />Move the Box<p></p></div> </div> <div id="respond"></div>
As you can see we just setup a very nice and simple page which calls in our CSS, JavaScript library and plugins, and contains the elements which we will be using to apply some effects and events to. As a note,the jquery-ui file is a custom build which only includes the core and the draggable interaction functionality.

The Javascript
Now for some juicy interaction! Lets first take a look at some of the basic functions we will be using to apply some effects to our elements. Let’s tear it down.
<script type="text/javascript">
$(document).ready(function() {
$("#element").draggable({
containment: '#glassbox',
scroll: false
})
First we tell the browser, “Hey, this is some code we want to run; it’s not HTML, it’s JavaScript.” We then want to wait for the document to load before we do anything else, once thats happened, we call a function to select our #element DIV, and add the draggable handler with some basic options. The containment options will keep our element within the parent DIV, and we set scroll to false because we don’t want any scrolling to happen. Let’s move on:
.mousemove(function(){
var coord = $(this).position();
$("p:last").text( "left: " + coord.left + ", top: " + coord.top );
})
With this tidbit, we call the event handler mousemove and tell it, “When the mouse moves, set the variable ‘coord’ to equal our selected #element’s position.” Then we select a paragraph (”p:last”), the last one in #element, and print some text which will read out the left(x) and the top(y) properties of our element relative to the parent object (which is #glassbox).
.mouseup(function(){
var coords=[];
var coord = $(this).position();
var item={ coordTop: coord.left, coordLeft: coord.top };
coords.push(item);
var order = { coords: coords };
$.post('updatecoords.php', 'data='+$.toJSON(order), function(response){
if(response=="success")
$("#respond").html('<div class="success">X and Y Coordinates Saved!</div>').hide().fadeIn(1000);
setTimeout(function(){ $('#respond').fadeOut(1000); }, 2000);
});
});
});
</script>
Ok now for some devilry! In this snippet we are going to do a couple of things. First we want to setup an empty array, and then get some values to fill it with. By calling the event handler .mouseup() we are telling the browser to look for the event when you unclick your mouse. We set the variable coords to equal our empty array, and again set the variable coord to equal the position handler of our #element. Then we need to create a list of items, these will be coordTop: and coordLeft: respectfully equaling our #element’s left and top positions. With coords.push(item) we are literally pushing our item list and filling the coords array with it. Then set the variable order as a new list where the coords key will equal our coords array. Now for some AJAX.

$.post is an AJAX request handler which loads a remote page using an HTTP POST method. This function looks for the parameters: url, data, callback and data type to be returned. In this tutorial we specify the updatecoords.php file as our URL because this is where we want to send our post data, we then define our datatype by including the $.toJSON function defined in our jquery-JSON plugin and setting our variable order as the data to be handled by .toJSON. Next we create a callback which checks for a return response from our PHP file upon success, and add a bit of flavor by saying, “If whats returned is equal to success then…” We keep this html hidden by using the effect handler .hide, and tell it to fade in at 1000 milliseconds, wait with a timeout for 2000 milliseconds, and tell it to fade out again. In the end our JavaScript should look like this:
<script type="text/javascript">
$(document).ready(function() {
$("#element").draggable({
containment: '#glassbox',
scroll: false
}).mousemove(function(){
var coord = $(this).position();
$("p:last").text( "left: " + coord.left + ", top: " + coord.top );
}).mouseup(function(){
var coords=[];
var coord = $(this).position();
var item={ coordTop: coord.left, coordLeft: coord.top };
coords.push(item);
var order = { coords: coords };
$.post('updatecoords.php', 'data='+$.toJSON(order), function(response){
if(response=="success")
$("#respond").html('<div class="success">X and Y Coordinates Saved!</div>').hide().fadeIn(1000);
setTimeout(function(){ $('#respond').fadeOut(1000); }, 2000);
});
});
});
</script>
Place the JavaScript below the HTML, right after the closing body tag.
The PHP
Alright, now lets get to business on doing something with the data being posted from our jQuery. First lets create a simple database to store our coordinates, which we will then later retrieve to define the position of our element. Second will be our config.php file which will store our database connection settings, and then we will finish with updatecords.php.
Database: 'xycoords' CREATE TABLE IF NOT EXISTS `coords` ( `id` int(11) NOT NULL AUTO_INCREMENT, `x_pos` int(4) NOT NULL, `y_pos` int(4) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
config.php
<?php
/*Database Settings*/
$db_host ="localhost"; //this will likely stay the same
$db_name = "xycoords"; //name of the database we will be using
$db_usr = "database_username"; //db username
$db_pass = "database_password"; //db password
//Connect to the database
$link = mysqli_connect($db_host, $db_usr, $db_pass) or die("MySQL Error: " . mysqli_error());
//Select our database
mysqli_select_db($link, $db_name) or die("MySQL Error: " . mysqli_error());
?>
updatecoords.php
<?php
if(!$_POST["data"]){
echo "Nothing Sent";
exit;
}
include ('config.php');
//decode JSON data received from AJAX POST request
$data = json_decode($_POST["data"]);
foreach($data->coords as $item) {
//Extract X number for panel
$coord_X = preg_replace('/[^\d\s]/', '', $item->coordTop);
//Extract Y number for panel
$coord_Y = preg_replace('/[^\d\s]/', '', $item->coordLeft);
//escape our values - as good practice
$x_coord = mysqli_real_escape_string($link, $coord_X);
$y_coord = mysqli_real_escape_string($link, $coord_Y);
//Setup our Query
$sql = "UPDATE coords SET x_pos = '$x_coord', y_pos = '$y_coord'";
//Execute our Query
mysqli_query($link, $sql) or die("Error updating Coords :".mysqli_error());
}
//Return Success
echo "success";
?>
This is pretty simple to follow. The first thing we want to do is check to make sure our post data is being passed to the file. If that happens we include our config file for our database connection and set the variable $data to json_decode(passed post variable); json_decode is a PHP function implemented in PHP 5.2.0 which allows us to decode a JSON string.
Since our $data variable contains an array of data, we need to tear it apart to get the values we need. To do this we take foreach $data->coords (which is from our order variable in our JavaScript) as an item. This takes each key and value pair and creates an item object from the array, we then specify and create a variable out of it. We use this in conjunction with preg_replace so that we can take out the characters we don’t need. We then, as good practice and a measure of security, escape our values to prepare them for insertion into the database. If all goes well, we need to return success to our JavaScript to let it know everything went just fine.

Lastly
Now that we have what we need in place, to grab the position coordinates from our element and pass it to PHP for storing, we need to modify our HTML to reflect the position of our element. To do this we change the basic element HTML and instead create it with PHP:
<div id="glassbox">
<?php
//Create a query to fetch our values from the database
$get_coords = mysqli_query($link, "SELECT * FROM coords");
//We then set variables from the * array that is fetched from the database
while($row = mysqli_fetch_array($get_coords)) {
$x = $row['x_pos'];
$y = $row['y_pos'];
//then echo our div element with CSS properties to set the left(x) and top(y) values of the element
echo '<div id="element" style="left:'.$x.'px; top:'.$y.'px;"><img src="nettuts.jpg" alt="Nettuts+" />Move the Box<p></p></div>';
}
?>
</div>
<div id="respond"></div>
Here we setup a basic query to the database to select all the rows from the table coords. We then invoke a while loop which specifies each row we select as $row. Now we can set some variables to equal each individual row we pull from the database, and echo them in the proper place within the elements style (left and top).
Wrapping up
Well I hope that you enjoyed this tutorial as much as I did writing it! It may not be perfect. While this is just one way to get this functionality in a draggable element, there are other ways (and perhaps better) to achieve it. Once such way could be to store the coordinate values in a cookie, to keep calls to the database at a minimum. You could also serialize the values passed from jQuery to PHP instead of using JSON. This tutorial is just one example from which you can expand upon. Thanks for reading!
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for the best web development tutorials on the web.



