lots of code take some code, share some code!



Market Music

Yesterday was the launch of the new market music website, the sellers of official music merchandise such as Misfits, Breaking Benjiman, Inflames and Many more. It was decided that the site would go live with only a few products that have been cleaned up from the old site and now they are hoping to add many products over the next couple of months.

Please take a look, let me know what you think.

- Music Band T-Shirt



Three Columns with Header, Menu and Footer

Simple template for inclusion into your website.



Simple Smarty Pagination

With the combined effort of my PHP Array Pagination script and this tutorial you will be able to pagination results (database & non database driven results) and intergrate it easily with the smarty template engine.

So, to start download the PHP Pagination script and then put it into a directory within your smarty setup.

During this example i am going to be using some test data, a basic PHP array with 10 sub array's, like so:

$myArray = array(
array('id' = > 1, 'title' => 'Test Item 1'),
array('id' = > 2, 'title' => 'Test Item 2'),
array('id' = > 3, 'title' => 'Test Item 3'),
array('id' = > 4, 'title' => 'Test Item 4'),
array('id' = > 5, 'title' => 'Test Item 5'),
array('id' = > 6, 'title' => 'Test Item 6'),
array('id' = > 7, 'title' => 'Test Item 7'),
array('id' = > 8, 'title' => 'Test Item 8'),
array('id' = > 9, 'title' => 'Test Item 9'),
array('id' = > 10, 'title' => 'Test Item 10'),
);

Then assign the pagination class to an object called pagination and assign the array and the amount of page numbers and assign this information into the smarty template vars, one for the listing of the items and another for the actual pagination.

$pagination = new pagination();
$myArray = $pagination->generate($myArray, 10);
$smarty->assign('listing', $myArray);
$smarty->assign('pagination', $pagination->links());

Then go into the template side of your setup and add the following code

{if !empty($listing)}
{if !empty($pagination)}
<div class="pagination">{$pagination}</div>
{/if}
{foreach item="item" from="$listing"}
<tr>
<td>{$item.id}</td>
<td>{$item.title}</td>
{/foreach}
{/if}

It's a pretty quick and simple solution to get you going as a beginner, good luck!

One of the main issues i found with using the smarty template engine is that there isn't enough documentation online!



Simple Modular Arithmetic with Smarty Template Engine

Something i take for granted in PHP is the use of Modular Arithmetic when display results in a grid like format.

Usually in php, i would do something like this to display three items per row

if ($count % 3 == 0) {

// Add Break / Clear here

}

So i assumed something like this would be available in smarty. After googling for a while i found a couple of solutions to this, however none of them were as simple as the PHP code above, so by playing about with the Smarty Template Engine, i managed to figure out a nice simple way, and here it is.

{assign var="mycount" value="1"} {*Initiate the mycount variable*}
{if $mycount++ % 3 == 0} {*Simular syntax to the above*}
// Add Break / Clear here
{/if}

So, as i found this so useful for displaying products on a current project, i thought it would be something other would really like to know about.



jQuery - Skinning HTML Select Boxes

Had enough of the same old operating system based select field style? Why not skin it up, this script allows you to apply a skin to a select box.

This tutorial is based on the original code i wrote, however this version is less buggier and has support for non JS enabled browsers!

Nice and simple to install, include the jQuery library and the select skin JS file and the CSS file like so.

<style>
<!--
@import url('./css/skinned-select.css');
//-->
</style>
<script src="./js/jquery.js" type="text/javascript"></script>
<script src="./js/jquery.skinned-select.js" type="text/javascript"></script>

Then just wrap a div with the class name of 'my-skinnable-select' around the select box, like so.

<div class="my-skinnable-select">
<select name="name">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
</div>

The form variables can be posted as usual, it's as easy as that, enjoy!

Please take a look at the demo or download the code and let me know what you think by using the contact form below.



jQuery for beginners

This is a little tutorial i put together to help people starting out with jQuery to learn the basics.

So, first things first. Pop over to http://docs.jquery.com/Downloading_jQuery and download the latest version in whatever form you prefer, Minified, Packed or Uncompressed. If you are not fussed then i would suggest the packed version.

No, the first thing you should do is create a specific testing area, for example c:jquery. Then in that folder extract the jquery file into it, if the name of the js file isn't jquery then i would suggest you rename it to jquery.js to make the name of the file nice and easy to remember.

Now, on to the html.

Create a file, with whatever name you prefer, i will call mine 'myfirstjquery.htm' in that file i have created basic html as follows, i have also included

the jquery js file.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My First jQuery Script with lotsofcode.com</title>
<script src="jquery.js"></script>
</head>
<body>
</body>
</html>

Now that we have the basic html we can start adding some Javascript.

Next, create a new div and assign an id to the div like so.

<div id="hello-lotsofcode">Hello LotsofCode</div>

Now, save the file, open it with a web browser and you should have a basic html page with the text 'hello Go back to your text editor and add the following

code to inbetween the opening and closing head tags.

<script>
$(document).ready(
function() {
// Code to be executed goes here ...
}
);
</script>

Everything that is called by jQuery needs to be wrapped in this loader above.

Now, to call the element we just created we simply use a CSS style declaration to call the element like so.

<script>
$(document).ready(
function() {
alert( $('#hello-lotsofcode').text() );
}
);
</script>

This should present you with an alert box with the words 'hello LotsofCode', now, we can change the text value by using a simular method like so

<script>
$(document).ready(
function() {
$('#hello-lotsofcode').text('Hello from the visitor');
}
);
</script>

Now, when you execute this code, you should see that your div has the content of hello from the visitor, this is because we used the method text with a value and assigned it to the id hello-lotsofcode element, it's pretty simple isn't it!

Now, to hide and display elements:

<script>
$(document).ready(
function() {
$('#hello-lotsofcode').text('Hello from the visitor').hide();
}
);
</script>

And to show ...

<script>
$(document).ready(
function() {
$('#hello-lotsofcode').text('Hello from the visitor').show();
}
);
</script>

The two above methods don't mean much on there own, but with an event handler we can have some fun.

So at the top of the page add two anchor links.

<a href="#" class="hide-text">Hide Text</a>
<a href="#" class="show-text">Show Text</a>

Then the jQuery code for this is as follows:

<script>
$(document).ready(
function() {
$('.hide-text').click(
function() {
$('#hello-lotsofcode').text('Hello from the visitor').hide();
}
);
$('.show-text').click(
function() {
$('#hello-lotsofcode').text('Hello from the visitor').show();
}
);
}
);
</script>

Nice results eh ... ? You can easily hide anddisplay elements on the page.

I did say this tutorial was for beginners and it is, i have emphasized on this because now i am going to show you some basic effects and i don't want you to assume they are going to be really complicated.

So, while working with the same file, we can add a nice fading effect to go along with our new text, like so:

<script>
$(document).ready(
function() {
$('#hello-lotsofcode').text('Hello from the visitor').hide().fadeIn('slow');
}
);
</script>

Note the chainability, all i have added is '.hide().fadeIn('slow')' to the end of the string so we hide the element and then immediately after we fade it in, take a look at the results.



Wordpress TinyMCE Image Upload Plugin

After many hours looking and looking for a plugin for TinyMCE i finally found one that actually worked quite well and was what it said it is .. An actual image upload plugin for Wordpress's TinyMCE ... !

Take a look here: http://www.soderlind.no/archives/2006/01/03/imagemanager-20/

Untitled_1.gif

Download here: http://www.soderlind.no/download/ImageManager2.41.zip

I know someone will really appreciate this post as i would appreciate someone else posting a link to such a great resourse, if anyone knows of any other open source / free plugins for TinyMCE please post here.

If PHP safe_mode is enabled on server you may find problems with thumbnails ...



Tag Cloud v2

Please check out the demo page for examples on how to use the new functions available in this version.

Some of the new features included in the new tag cloud script are:

  • Link and URL Assignment
  • Additional attribute assignment e.g. title etc
  • Add styles and colour options to each tag
  • Set a limit to the amount of tags that are displayed
  • Examples of intergrating with a MySQL Database
  • Examples of intergrating with a Flat Text File
  • String to cloud, parse a single string into a tag cloud instantly
  • Ignore list, to remove particular words from the cloud. e.g. and, the, it, i
  • Ordering by a selective field. e.g. word, size, colour

Tutorial coming soon ...



Tag Cloud

Tag Cloud Script (Version 2) is now Available, with more customizable features

Introduction


In this tutorial i am going to show you how to create a basic word / tag cloud using php and utilizing php classes for easy inclusion. I am going to create a class based cloud, this is because it will be more convenient for you to adapt it on your own website(s), if you don't know much about class based programming then click here to take a look at the class tutorial.

Tutorial

First we need to create the class and for this example i am going to call the class 223wordCloud224 this is just my personal naming preference, feel free to call your cloud whatever you like, we are also going to assign the first class variable which will be the container of all the items in the array, we will call it 223wordsArray224.

<?
class wordcloud
{
var $wordsArray = array();
}
?>

Next, we need to assign the first function, because of the difference between PHP 4 and PHP 5 Constructors, i have created a method (function) called 223wordCloud224 and 223__construct224, when wordCloud is called it simultaneously call the PHP 5 constructor, so it's compatible with both versions like so.

<?
function __construct($words = false)
{
if ($words !== false && is_array($words))
{
foreach ($words as $key => $value)
{
$this->addWord($value);
}
}
}

function wordCloud($words = false)
{
$this->__construct($words);
}
?>

The main constructor basically can be used to load the words when the class object is created.

Now, we need to create a function to add words into the array as and when we need them.

<?
function addWord($word, $value = 1)
{
$word = strtolower($word);
if (array_key_exists($word, $this->wordsArray))
$this->wordsArray[$word] += $value;
else
$this->wordsArray[$word] = $value;

return $this->wordsArray[$word];
}
?>

The method above will basically check the array of words and if the word exists it will increase the repetition value, this can also be adjusted by manual input.

Next, we need to be able to get the size of the array, now because we have an array with values, we can use the values of all the items in the array added together like so.

<?
function getCloudSize()
{
return array_sum($this->wordsArray);
}
?>

Next, we need to create a function to calculate the class / range that each specific word should be assigned to, this will be done by using the percentage that will be returned from the final function.

<?
function getClassFromPercent($percent)
{
if ($percent >= 99)
$class = 1;
else if ($percent >= 70)
$class = 2;
else if ($percent >= 60)
$class = 3;
else if ($percent >= 50)
$class = 4;
else if ($percent >= 40)
$class = 5;
else if ($percent >= 30)
$class = 6;
else if ($percent >= 20)
$class = 7;
else if ($percent >= 10)
$class = 8;
else if ($percent >= 5)
$class = 9;
else
$class = 0;

return $class;
}
?>

Next we create a function that will shuffle all the values in the cloud, this is so that we can have a different output each time, this could be adapted so that it only shuffles the cloud if choose to.

<?
function shuffleCloud()
{
$keys = array_keys($this->wordsArray);

shuffle($keys);

if (count($keys) && is_array($keys))
{
$tmpArray = $this->wordsArray;
$this->wordsArray = array();
foreach ($keys as $key => $value)
$this->wordsArray[$value] = $tmpArray[$value];
}
}
?>

Now, we need to create a function to display the words, i have decided to make this function have two possible outputs, this is because if you would like more control over the output or if you would like to use less standard class names then you can do so, the two possible output types are an php array and html spans.

function showCloud($returnType = "html")
{
$this->shuffleCloud();
$this->fullCloudSize = $this->getCloudSize();
$this->max = max($this->wordsArray);

if (is_array($this->wordsArray))
{
$return = ($returnType == "html" ? "" : ($returnType == "array" ? array() : ""));
foreach ($this->wordsArray as $word => $popularity)
{
$sizeRange = $this->getClassFromPercent(($popularity / $this->max) * 100);
if ($returnType == "array")
{
$return[$word]['word'] = $word;
$return[$word]['sizeRange'] = $sizeRange;
if ($currentColour)
$return[$word]['randomColour'] = $currentColour;
}
else if ($returnType == "html")
{
$return .= "<span class='word size{$sizeRange}'> {$word} </span>";
}
}

return $return;
}
}

Ok, so now we have the class, we need to use this to create our cloud, this could be done like so.

<?

// You could add items to the class by passing them through the constructor

$randomWords = array("webmasterworld", "Computer", "Skateboarding", "PC", "music", "music", "music", "music", "PHP", "C", "XHTML", "programming", "forums", "Chill out", "email", "forums", "Computer", "GTA", "Freetimers", "css", "mysql", "sql", "css", "mysql", "sql", "forums", "internet", "class", "object", "method", "music", "music", "music", "music", "gui", "encryption");

$cloud = new wordCloud($randomWords);

// Or you could assign them manually
$cloud->addWord("harvey", 5);
$cloud->addWord("music", 12);
echo $cloud->showCloud();
?>

Don't forget to create your styles to display the different size fonts, this is a little something i have come up with.

<style>
<!--
.word {
font-family: Tahoma;
padding: 4px 4px 4px 4px;
letter-spacing: 3px;
}
span.size1 {
color: #000;
font-size: 2.4em;
}
span.size2 {
color: #333;
font-size:2.2em;
}
span.size3 {
color: #666;
font-size: 2.0em;
}
span.size4 {
color: #999;
font-size: 1.0em;
}
span.size5 {
color: #aaa;
font-size: 1.6em;
}
span.size6 {
color: #bbb;
font-size: 1.4em;
}
span.size7 {
color: #ccc;
font-size: 1.2em;
}
span.size8 {
color: #ddd;
font-size: .8em;
}
//-->
</style>

To finish off i will finish with the code in full.

Full PHP Tag Cloud Class

<?
/*
@wordCloud
Author: Derek Harvey
Website: www.lotsofcode.com

@Description
PHP Tag Cloud Class, a nice and simple way to create a php tag cloud, a database and non-database solution.
*/

class wordCloud
{
var $wordsArray = array();

/*
* PHP 5 Constructor
*
* @param array $words
* @return void
*/

function __construct($words = false)
{
if ($words !== false && is_array($words))
{
foreach ($words as $key => $value)
{
$this->addWord($value);
}
}
}

/*
* PHP 4 Constructor
*
* @param array $words
* @return void
*/

function wordCloud($words = false)
{
$this->__construct($words);
}

/*
* Assign word to array
*
* @param string $word
* @return string
*/

function addWord($word, $value = 1)
{
$word = strtolower($word);
if (array_key_exists($word, $this->wordsArray))
$this->wordsArray[$word] += $value;
else
$this->wordsArray[$word] = $value;

return $this->wordsArray[$word];
}

/*
* Shuffle associated names in array
*/

function shuffleCloud()
{
$keys = array_keys($this->wordsArray);

shuffle($keys);

if (count($keys) && is_array($keys))
{
$tmpArray = $this->wordsArray;
$this->wordsArray = array();
foreach ($keys as $key => $value)
$this->wordsArray[$value] = $tmpArray[$value];
}
}

/*
* Calculate size of words array
*/

function getCloudSize()
{
return array_sum($this->wordsArray);
}

/*
* Get the class range using a percentage
*
* @returns int $class
*/

function getClassFromPercent($percent)
{
if ($percent >= 99)
$class = 1;
else if ($percent >= 70)
$class = 2;
else if ($percent >= 60)
$class = 3;
else if ($percent >= 50)
$class = 4;
else if ($percent >= 40)
$class = 5;
else if ($percent >= 30)
$class = 6;
else if ($percent >= 20)
$class = 7;
else if ($percent >= 10)
$class = 8;
else if ($percent >= 5)
$class = 9;
else
$class = 0;

return $class;
}

/*
* Create the HTML code for each word and apply font size.
*
* @returns string $spans
*/

function showCloud($returnType = "html")
{
$this->shuffleCloud();
$this->max = max($this->wordsArray);

if (is_array($this->wordsArray))
{
$return = ($returnType == "html" ? "" : ($returnType == "array" ? array() : ""));
foreach ($this->wordsArray as $word => $popularity)
{
$sizeRange = $this->getClassFromPercent(($popularity / $this->max) * 100);
if ($returnType == "array")
{
$return[$word]['word'] = $word;
$return[$word]['sizeRange'] = $sizeRange;
if ($currentColour)
$return[$word]['randomColour'] = $currentColour;
}
else if ($returnType == "html")
{
$return .= "<span class='word size{$sizeRange}'> {$word} </span>";
}
}
return $return;
}
}
}
?>

<style>
<!--
.word {
font-family: Tahoma;
padding: 4px 4px 4px 4px;
letter-spacing: 3px;
}
span.size1 {
color: #000;
font-size: 2.4em;
}
span.size2 {
color: #333;
font-size:2.2em;
}
span.size3 {
color: #666;
font-size: 2.0em;
}
span.size4 {
color: #999;
font-size: 1.0em;
}
span.size5 {
color: #aaa;
font-size: 1.6em;
}
span.size6 {
color: #bbb;
font-size: 1.4em;
}
span.size7 {
color: #ccc;
font-size: 1.2em;
}
span.size8 {
color: #ddd;
font-size: .8em;
}
span.size0 {
color: #ccc;
font-size: .6em;
}
//-->
</style>

<?
$randomWords = array(
"webmasterworld", "Computer", "Skateboarding", "PC", "music", "music", "music", "music", "PHP", "C", "XHTML", "eminem", "programming", "forums", "webmasterworld",
"Chill out", "email", "forums", "Computer", "GTA", "css", "mysql", "sql", "css", "mysql", "sql",
"forums", "internet", "class", "object", "method", "music", "music", "music", "music", "gui", "encryption"
);

$cloud = new wordCloud($randomWords);
$cloud->addWord("music", 12);
$cloud->addWord("downloads", 8);
$cloud->addWord("internet", 17);
$cloud->addWord("PHP", 22);
$cloud->addWord("CSS", 32);
echo $cloud->showCloud();
?>

And this is how it should look, i have changes some of the colours for the more important words.

How to intergrate with a MySQL database.

Depending on how your information is stored in your database, an individual field or a comma seperated field then you can place the tags into the cloud from a MySQL results like follows.

Let's say we have a table called tags, if we have comma seperated values.

<?php

$cloud = new wordcloud();

$getBooks = mysql_query("SELECT title FROM `tags`");
if ($getBooks)
{
while ($rowBooks = mysql_fetch_assoc($getBooks))
{
$getTags = explode(' ', $rowBooks['title']);
foreach ($getTags as $key => $value)
{
$value = trim($value);
$cloud->addWord($value);
}
}
}

$myCloud = $cloud->showCloud('array');
if (is_array($myCloud))
{
foreach ($myCloud as $key => $value)
{
echo ' <a href="path/to/tags/'.$value['word'].'" style="font-size: 1.'.$value['sizeRange'].'em">'.$value['word'].'</a> &nbsp;';
}

?>

If the tag is an individual field, then:

<?php

$cloud = new wordcloud();

$getBooks = mysql_query("SELECT title FROM `tags`");
if ($getBooks)
{
while ($rowBooks = mysql_fetch_assoc($getBooks))
{
$cloud->addWord($rowBooks['title']);
}
}
}

$myCloud = $cloud->showCloud('array');
if (is_array($myCloud))
{
foreach ($myCloud as $key => $value)
{
echo ' <a href="tags_url/'.urlencode($value['word']).'" style="font-size: 1.'.($value['range']).'em">'.$value['word'].'</a> ';
}
?>

Video Tutorials

Finished.

Ok, so that's the tutorial over. Please have fun with the code, if you are a little confused then please check out the video tutorials, the quality is a little bad at the moment but i hope to arrange some better videos soon!

All comments and questions are welcome, provided they are related to this page.



Select Insert Statement

A very simple way of passing data from one table to another is by using the select insert statement in sql.

INSERT INTO table (forename, dayphone, address1, address2, address3, postcode, country, email)
select r.first_name r.phone_number, r.address1, r.address2, r.address3, r.post_code, r.country, r.email from table2 r;