Given a directory, how to display the contents (directories and files under it) of it recursively and exhaustively? Here’s the code:

$dir = '/path/to/directory'; // without trailing slash, can be absolute paths such as '/home/jim/public_html' or relative paths such as 'samples'

getDirContents($dir);

function getDirContents($dir) {
	if (is_dir($dir)) {
		$dirs = explode('/', $dir);
		$last_dir = $dirs[count($dirs) - 1];
		echo '<strong>'.$last_dir.'</strong>';
	    if ($dh = opendir($dir)) {
	    	echo '<ul>';
	        while (($file = readdir($dh)) !== false) {
	        	if ($file == '.' || $file == '..') {} else {
		        	echo '<li>';
		        	if (is_dir($dir.'/'.$file)) {
		        		getDirContents($dir.'/'.$file);
		        	} else {
		        		echo $file;
		        	}
		        	echo '</li>';
	        	}
	        }
	        echo '</ul>';
	        closedir($dh);
	    }
	}
	return false;
}

Recursively, the function getDirContents() explores every entry in the directory. If the entry is a file, it simply prints it; if it is a directory, it opens another subroutine of itself to explore that directory; and so forth, until every branch and sub-branches, etc. are all printed out.

{ Comments on this entry are closed }

I was trying to find a PHP function or class that can convert English words / nouns in plural form into their singular form so that wordcrow.com automatically detects and redirects plural lookup to the singular page. After a while searching on Google, I found this class.

This great class (Inflector) was ported from Ruby on Rails to PHP in the Akelos Framework by Akelos Media, S.L. http://www.akelos.com/.

List of Functions

Other than pluralize and singularize, this class has some more functions to convert text strings by certain standards. List below are all the functions this class has:

  • Inflector::pluralize – return the plural form of the given English word, e.g. “search” to “searches”.
  • Inflector::singularize – return the singular form of the given English word, e.g. “searches” to “search”.
  • Inflector::titleize – create a title text from the given string, e.g. “WelcomePage”, “welcome_page” or “welcome page” to “Welcome Page”.
  • Inflector::camelize – return the CamelCased text from the given string, e.g. “send_email” to “SendEmail”, “who’s online” to “WhoSOnline”.
  • Inflector::underscore – return a underscored text from the given string, e.g. “CamelCased” or “ordinary Word” to “underscored_word” that is lowercased.
  • Inflector::humanize – return a human-readable text from the given string, e.g., by replacing underscores with spaces, and by upper-casing the initial character by default.
  • Inflector::variablize – same as camelize but first char is underscored.
  • Inflector::tableize – converts a class name to its table name by rails naming conventions.
  • Inflector::classify – converts a table name to its class name by rails naming conventions.
  • Inflector::ordinalize – converts a natural number to its ordinal form in English, e.g. “2” to “2nd”, “15” to “15th”, “31” to “31st”.

Inflector Class

<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

// +----------------------------------------------------------------------+
// | Akelos PHP Application Framework                                     |
// +----------------------------------------------------------------------+
// | Copyright (c) 2002-2006, Akelos Media, S.L.  http://www.akelos.com/  |
// | Released under the GNU Lesser General Public License                 |
// +----------------------------------------------------------------------+
// | You should have received the following files along with this library |
// | - COPYRIGHT (Additional copyright notice)                            |
// | - DISCLAIMER (Disclaimer of warranty)                                |
// | - README (Important information regarding this library)              |
// +----------------------------------------------------------------------+

/**
* Inflector for pluralize and singularize English nouns.
*
* This Inflector is a port of Ruby on Rails Inflector.
*
* It can be really helpful for developers that want to
* create frameworks based on naming conventions rather than
* configurations.
*
* It was ported to PHP for the Akelos Framework, a
* multilingual Ruby on Rails like framework for PHP that will
* be launched soon.
*
* @author Bermi Ferrer Martinez 
* @copyright Copyright (c) 2002-2006, Akelos Media, S.L. http://www.akelos.org
* @license GNU Lesser General Public License 
* @since 0.1
* @version $Revision 0.1 $
*/
class Inflector
{
    // ------ CLASS METHODS ------ //

    // ---- Public methods ---- //

    // {{{ pluralize()

    /**
    * Pluralizes English nouns.
    *
    * @access public
    * @static
    * @param    string    $word    English noun to pluralize
    * @return string Plural noun
    */
    function pluralize($word)
    {
        $plural = array(
        '/(quiz)$/i' => '1zes',
        '/^(ox)$/i' => '1en',
        '/([m|l])ouse$/i' => '1ice',
        '/(matr|vert|ind)ix|ex$/i' => '1ices',
        '/(x|ch|ss|sh)$/i' => '1es',
        '/([^aeiouy]|qu)ies$/i' => '1y',
        '/([^aeiouy]|qu)y$/i' => '1ies',
        '/(hive)$/i' => '1s',
        '/(?:([^f])fe|([lr])f)$/i' => '12ves',
        '/sis$/i' => 'ses',
        '/([ti])um$/i' => '1a',
        '/(buffal|tomat)o$/i' => '1oes',
        '/(bu)s$/i' => '1ses',
        '/(alias|status)/i'=> '1es',
        '/(octop|vir)us$/i'=> '1i',
        '/(ax|test)is$/i'=> '1es',
        '/s$/i'=> 's',
        '/$/'=> 's');

        $uncountable = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep');

        $irregular = array(
        'person' => 'people',
        'man' => 'men',
        'child' => 'children',
        'sex' => 'sexes',
        'move' => 'moves');

        $lowercased_word = strtolower($word);

        foreach ($uncountable as $_uncountable){
            if(substr($lowercased_word,(-1*strlen($_uncountable))) == $_uncountable){
                return $word;
            }
        }

        foreach ($irregular as $_plural=> $_singular){
            if (preg_match('/('.$_plural.')$/i', $word, $arr)) {
                return preg_replace('/('.$_plural.')$/i', substr($arr[0],0,1).substr($_singular,1), $word);
            }
        }

        foreach ($plural as $rule => $replacement) {
            if (preg_match($rule, $word)) {
                return preg_replace($rule, $replacement, $word);
            }
        }
        return false;

    }

    // }}}
    // {{{ singularize()

    /**
    * Singularizes English nouns.
    *
    * @access public
    * @static
    * @param    string    $word    English noun to singularize
    * @return string Singular noun.
    */
    function singularize($word)
    {
        $singular = array (
        '/(quiz)zes$/i' => '\1',
        '/(matr)ices$/i' => '\1ix',
        '/(vert|ind)ices$/i' => '\1ex',
        '/^(ox)en/i' => '\1',
        '/(alias|status)es$/i' => '\1',
        '/([octop|vir])i$/i' => '\1us',
        '/(cris|ax|test)es$/i' => '\1is',
        '/(shoe)s$/i' => '\1',
        '/(o)es$/i' => '\1',
        '/(bus)es$/i' => '\1',
        '/([m|l])ice$/i' => '\1ouse',
        '/(x|ch|ss|sh)es$/i' => '\1',
        '/(m)ovies$/i' => '\1ovie',
        '/(s)eries$/i' => '\1eries',
        '/([^aeiouy]|qu)ies$/i' => '\1y',
        '/([lr])ves$/i' => '\1f',
        '/(tive)s$/i' => '\1',
        '/(hive)s$/i' => '\1',
        '/([^f])ves$/i' => '\1fe',
        '/(^analy)ses$/i' => '\1sis',
        '/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis',
        '/([ti])a$/i' => '\1um',
        '/(n)ews$/i' => '\1ews',
        '/s$/i' => '',
        );

        $uncountable = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep');

        $irregular = array(
        'person' => 'people',
        'man' => 'men',
        'child' => 'children',
        'sex' => 'sexes',
        'move' => 'moves');

        $lowercased_word = strtolower($word);
        foreach ($uncountable as $_uncountable){
            if(substr($lowercased_word,(-1*strlen($_uncountable))) == $_uncountable){
                return $word;
            }
        }

        foreach ($irregular as $_plural=> $_singular){
            if (preg_match('/('.$_singular.')$/i', $word, $arr)) {
                return preg_replace('/('.$_singular.')$/i', substr($arr[0],0,1).substr($_plural,1), $word);
            }
        }

        foreach ($singular as $rule => $replacement) {
            if (preg_match($rule, $word)) {
                return preg_replace($rule, $replacement, $word);
            }
        }

        return $word;
    }

    // }}}
    // {{{ titleize()

    /**
    * Converts an underscored or CamelCase word into a English
    * sentence.
    *
    * The titleize function converts text like "WelcomePage",
    * "welcome_page" or  "welcome page" to this "Welcome
    * Page".
    * If second parameter is set to 'first' it will only
    * capitalize the first character of the title.
    *
    * @access public
    * @static
    * @param    string    $word    Word to format as tile
    * @param    string    $uppercase    If set to 'first' it will only uppercase the
    * first character. Otherwise it will uppercase all
    * the words in the title.
    * @return string Text formatted as title
    */
    function titleize($word, $uppercase = '')
    {
        $uppercase = $uppercase == 'first' ? 'ucfirst' : 'ucwords';
        return $uppercase(Inflector::humanize(Inflector::underscore($word)));
    }

    // }}}
    // {{{ camelize()

    /**
    * Returns given word as CamelCased
    *
    * Converts a word like "send_email" to "SendEmail". It
    * will remove non alphanumeric character from the word, so
    * "who's online" will be converted to "WhoSOnline"
    *
    * @access public
    * @static
    * @see variablize
    * @param    string    $word    Word to convert to camel case
    * @return string UpperCamelCasedWord
    */
    function camelize($word)
    {
        return str_replace(' ','',ucwords(preg_replace('/[^A-Z^a-z^0-9]+/',' ',$word)));
    }

    // }}}
    // {{{ underscore()

    /**
    * Converts a word "into_it_s_underscored_version"
    *
    * Convert any "CamelCased" or "ordinary Word" into an
    * "underscored_word".
    *
    * This can be really useful for creating friendly URLs.
    *
    * @access public
    * @static
    * @param    string    $word    Word to underscore
    * @return string Underscored word
    */
    function underscore($word)
    {
        return  strtolower(preg_replace('/[^A-Z^a-z^0-9]+/','_',
        preg_replace('/([a-zd])([A-Z])/','1_2',
        preg_replace('/([A-Z]+)([A-Z][a-z])/','1_2',$word))));
    }

    // }}}
    // {{{ humanize()

    /**
    * Returns a human-readable string from $word
    *
    * Returns a human-readable string from $word, by replacing
    * underscores with a space, and by upper-casing the initial
    * character by default.
    *
    * If you need to uppercase all the words you just have to
    * pass 'all' as a second parameter.
    *
    * @access public
    * @static
    * @param    string    $word    String to "humanize"
    * @param    string    $uppercase    If set to 'all' it will uppercase all the words
    * instead of just the first one.
    * @return string Human-readable word
    */
    function humanize($word, $uppercase = '')
    {
        $uppercase = $uppercase == 'all' ? 'ucwords' : 'ucfirst';
        return $uppercase(str_replace('_',' ',preg_replace('/_id$/', '',$word)));
    }

    // }}}
    // {{{ variablize()

    /**
    * Same as camelize but first char is underscored
    *
    * Converts a word like "send_email" to "sendEmail". It
    * will remove non alphanumeric character from the word, so
    * "who's online" will be converted to "whoSOnline"
    *
    * @access public
    * @static
    * @see camelize
    * @param    string    $word    Word to lowerCamelCase
    * @return string Returns a lowerCamelCasedWord
    */
    function variablize($word)
    {
        $word = Inflector::camelize($word);
        return strtolower($word[0]).substr($word,1);
    }

    // }}}
    // {{{ tableize()

    /**
    * Converts a class name to its table name according to rails
    * naming conventions.
    *
    * Converts "Person" to "people"
    *
    * @access public
    * @static
    * @see classify
    * @param    string    $class_name    Class name for getting related table_name.
    * @return string plural_table_name
    */
    function tableize($class_name)
    {
        return Inflector::pluralize(Inflector::underscore($class_name));
    }

    // }}}
    // {{{ classify()

    /**
    * Converts a table name to its class name according to rails
    * naming conventions.
    *
    * Converts "people" to "Person"
    *
    * @access public
    * @static
    * @see tableize
    * @param    string    $table_name    Table name for getting related ClassName.
    * @return string SingularClassName
    */
    function classify($table_name)
    {
        return Inflector::camelize(Inflector::singularize($table_name));
    }

    // }}}
    // {{{ ordinalize()

    /**
    * Converts number to its ordinal English form.
    *
    * This method converts 13 to 13th, 2 to 2nd ...
    *
    * @access public
    * @static
    * @param    integer    $number    Number to get its ordinal value
    * @return string Ordinal representation of given string.
    */
    function ordinalize($number)
    {
        if (in_array(($number % 100),range(11,13))){
            return $number.'th';
        }else{
            switch (($number % 10)) {
                case 1:
                return $number.'st';
                break;
                case 2:
                return $number.'nd';
                break;
                case 3:
                return $number.'rd';
                default:
                return $number.'th';
                break;
            }
        }
    }

    // }}}

}

?>

Usage Examples

/* Singular to plural / Plural to singular */

echo Inflector::pluralize('search'); // outputs searches
echo Inflector::singularize('cases'); // outputs case
echo Inflector::pluralize('query'); // outputs queries
echo Inflector::singularize('queries'); // outputs query
echo Inflector::pluralize('ability'); // outputs abilities
echo Inflector::singularize('abilities'); // outputs ability
echo Inflector::pluralize('analysis'); // outputs analyses
echo Inflector::singularize('analyses'); // outputs analysis
echo Inflector::pluralize('information'); // outputs information
echo Inflector::singularize('information'); // outputs information
echo Inflector::pluralize('mouse'); // outputs mice
echo Inflector::singularize('mice'); // outputs mouse

/* CamelCase to underscore / underscore to CamelCase */

echo Inflector::underscore('SpecialGuest'); // outputs special_guest
echo Inflector::camelize('special_guest'); // outputs SpecialGuest
echo Inflector::underscore('FreeBSD'); // outputs free_bsd
echo Inflector::camelize('free_bsd'); // outputs FreeBsd
echo Inflector::underscore('HTML'); // outputs html
echo Inflector::camelize('html'); // outputs Html

/* Underscore to "human-text" / "Human-text" to Underscore */

echo Inflector::humanize('employee_salary'); // outputs Employee salary
echo Inflector::underscore('Employee salary'); // outputs employee_salary

/* Examples of titleize() */

echo Inflector::titleize('ActiveRecord'); // outputs Active Record
echo Inflector::titleize('action web service'); // outputs Action Web Service

/* Examples of ordinalize() */

echo Inflector::ordinalize(1); // outputs 1st
echo Inflector::ordinalize(2); // outputs 2nd
echo Inflector::ordinalize(3); // outputs 3rd
echo Inflector::ordinalize(4); // outputs 4th
echo Inflector::ordinalize(5); // outputs 5th
echo Inflector::ordinalize(20); // outputs 20th
echo Inflector::ordinalize(21); // outputs 21st

{ Comments on this entry are closed }

amazon affiliate earning stats screenshot I’ve been a happy Amazon affiliate for over a year now and the monthly revenues have been steadily climbing up ever since I started promoting their products galore. The most recent month, Mar. 2011 has ended up making me over $400 in commissions or advertising fees. Attached on the right is the screenshot. Considering I didn’t do much work, it’s really awesome to have a nice side income that’s gonna last for a while – which is the beauty of SEO! Once you done the hard work the right way, it’s gonna last for at least a few years and even grow by itself!

So I’ve got a few tips to share with you if you just started on Amazon to make money.

If you’ve got a blog:

These are tips for people who aren’t technically oriented but blog a lot.

  1. Don’t promote a product or widget on a site-wide level. My experience is it almost never works out. Go article level.
  2. Add a relevant product at the end of every blog post. It takes extra minutes for a post but it would definitely yield great results. Relevance is the key here. Find the most reviewed and best received product such as a book that carries the information relevant to your blog post. Find the product that best complements your post.
  3. Write articles in the mind of promoting one or more of the popular products at Amazon. Do not write to hype how good the product is, instead, write in your genuine tone to solve the readers’ or visitors’ problem and drop your Amazon affiliate links in-between the helpful words, naturally leading them to purchase the products.
  4. If you’ve used a product, write a genuine review! People love personal writings. Write a review and be personal. Then link to Amazon page under your affiliate ID.
  5. Target micro-niches and go long tail. The smallest product (in terms of price) would make you the most money. Most people who fail in Internet marketing fail to realize this. Small is big.

If you know how to build a website all by yourself:

These are tips for people who develop websites by themselves.

  1. Create a comparison shopping site / search engine that integrates a lot of different vendors. Visitors arrive on your page to compare the prices and terms of each vendor (including Amazon’s) and decide where to spend the money – by clicking your affiliate links. This is the mogul approach. It is great but you have to dedicate a lot of time and energy to make and maintain it. I built Dante Books off this ISBN database which is essentially a books directory site with limited price comparison. For now, it leads only to Amazon. 😉
  2. Add relevant products to your existing sites. For example, the traffic of a golf courses directory would be very much interested in the golf equipment.
  3. Create a review club of certain products. People can come to share their reviews. An online book club would be very fun to create and maintain!
  4. Create a rebate site. When customers order under your name and you earn 7% of the deal, give 3% rebate to the customer.

To make the most of Amazon Associate Program or any other affiliate programs:

Some general guidelines in making affiliate programs work.

  1. Use a clean, white design with minimum images unless it’s for the sale / conversion.
  2. Put content the first thing. Do NOT distract the readers from the content for any reason. Get rid of other ads. Less is more.
  3. Blend your affiliate links in the content as if it’s a very helpful and indispensable resource to compensate your point.
  4. Write the content within 2-minutes reading time’s length. Use at least one list, ordered or unordered, in each article. Plant at least one affiliate link in the list.

There could be more, but I’ve got to find something to eat now.

{ Comments on this entry are closed }

When people are replying to a thread, going advanced editing would require an extra click as well as page loading time – very inconvenient. However, at gotalk.org, users would generally want to post a lot of code because it’s a programming language forum in nature. But vBulletin doesn’t come with a CODE button in the quick reply editor toolbar by default.

So I’ll have to add the CODE button to the quick reply box myself.

How to add extra buttons to the toolbar of the quick reply editor? (v4.1.2)

Just copy and paste the buttons code from the advanced editor to the quick reply editor. The advanced editor template is “editor_toolbar_on” while that of the quick reply editor is “showthread_quickreply”. All we have to do is to copy some code from “editor_toolbar_on” to “showthread_quickreply”.

In the example below, I’ll add the CODE button from the advanced editor to the quick reply editor. You can add other buttons to the quick reply box in similar steps.

1. Open “editor_toolbar_on” template

From /admincp, Styles & Templates –> Style Manager –> click “Search in Templates” –> in the “Search for Text” box, enter “editor_toolbar_on” –> click “Find” –> double click “editor_toolbar_on” in the left selection.

2. Open “showthread_quickreply” template

From /admincp, Styles & Templates –> Style Manager –> click “Search in Templates” –> in the “Search for Text” box, enter “showthread_quickreply” –> click “Find” –> double click “showthread_quickreply” in the left selection.

3. Find the code for CODE button in the “editor_toolbar_on” template

Simply search for:

$show['code_bbcode']

In the “editor_toolbar_on” template and you would find a code block like this:

<vb:if condition="$show['code_bbcode'] OR $show['html_bbcode'] OR $show['php_bbcode']"> <li> <vb:if condition="$show['code_bbcode']"><img src="{vb:stylevar imgdir_editor}/code.png" class="imagebutton" id="{vb:raw editorid}_cmd_wrap0_code" width="20" height="20" alt="{vb:rawphrase wrap_code_tags}" /></vb:if> <vb:if condition="$show['html_bbcode']"><img src="{vb:stylevar imgdir_editor}/html.png" class="imagebutton" id="{vb:raw editorid}_cmd_wrap0_html" width="20" height="20" alt="{vb:rawphrase wrap_html_tags}" /></vb:if> <vb:if condition="$show['php_bbcode']"><img src="{vb:stylevar imgdir_editor}/php.png" class="imagebutton" id="{vb:raw editorid}_cmd_wrap0_php" width="20" height="20" alt="{vb:rawphrase wrap_php_tags}" /></vb:if> </li> </vb:if>

Copy this code block, and switch to the “showthread_quickreply” template.

4. Add the code in the “showthread_quickreply” template

Search for:

$show['quote_bbcode']

And you would find the code for the QUOTE button:

<vb:if condition="$show['quote_bbcode']"> <li class="editor_control_group_item"> <img src="{vb:stylevar imgdir_editor}/quote.png" class="imagebutton" id="{vb:raw editorid}_cmd_wrap0_quote" width="20" height="20" alt="{vb:rawphrase wrap_quote_tags}" /> </li> </vb:if>

Immediately below the QUOTE button block, paste what you just copied from the “editor_toolbar_on” template, and add a class=”editor_control_group_item” to the <li> element:

<vb:if condition="$show['quote_bbcode']"> <li class="editor_control_group_item"> <img src="{vb:stylevar imgdir_editor}/quote.png" class="imagebutton" id="{vb:raw editorid}_cmd_wrap0_quote" width="20" height="20" alt="{vb:rawphrase wrap_quote_tags}" /> </li> </vb:if> <vb:if condition="$show['code_bbcode'] OR $show['html_bbcode'] OR $show['php_bbcode']"> <li class="editor_control_group_item"> <vb:if condition="$show['code_bbcode']"><img src="{vb:stylevar imgdir_editor}/code.png" class="imagebutton" id="{vb:raw editorid}_cmd_wrap0_code" width="20" height="20" alt="{vb:rawphrase wrap_code_tags}" /></vb:if> <vb:if condition="$show['html_bbcode']"><img src="{vb:stylevar imgdir_editor}/html.png" class="imagebutton" id="{vb:raw editorid}_cmd_wrap0_html" width="20" height="20" alt="{vb:rawphrase wrap_html_tags}" /></vb:if> <vb:if condition="$show['php_bbcode']"><img src="{vb:stylevar imgdir_editor}/php.png" class="imagebutton" id="{vb:raw editorid}_cmd_wrap0_php" width="20" height="20" alt="{vb:rawphrase wrap_php_tags}" /></vb:if> </li> </vb:if>

Click “Save” or “Save and Reload”. Done!

Now refresh any thread page and you’ll see the CODE button as well as the HTML code button and PHP code button are all added to the toolbar of the quick reply editor. Following the same steps, you can add other buttons from the advanced editor to the quick reply editor.

(This is for vBulletin 4.1.2)

{ Comments on this entry are closed }

The quick reply box of vBulletin is by default about 100px or less in height which is bit small for large chunks of text editing such as code. To change the default height of the quick reply box without having to click the enlarge button manually every time, you’ll have to edit the template:

Changing default height of quick reply box

After you have logged in the /admincp:

Styles & Templates –> Style Manager –> Edit Templates (in the dropdown menu) –> double click Show Thread Templates (in the left selection of all the templates) –> double click “showthread_quickreply” –> search for “rows=” and you will arrive at the line you should edit.

However, just updating the rows property to a larger one won’t work, you have to manually add a style property like this:

rows="10" tabindex="1" cols="80" style="height:25em;" dir="{vb:stylevar textdirection}"

25em indicates that the quick reply box will be able to accommodate 40 lines of text within one scroll.

Now click “Save”.

Changing default height of advanced editor

The steps to change the default height or size of the advanced message editor in vBulletin goes similar. Instead of “showthread_quickreply”, just search for “editor_toolbar_on”. Search for “row=” or “textarea” and you will find the editor control. Add a style property just the same:

rows="10" tabindex="1" cols="80" style="height:40em;" dir="{vb:stylevar textdirection}"

These steps are for vBulletin 4.1.2. Some of the tutorials you can find for changing the default height of the editing boxes are a bit outdated and for older versions.

{ Comments on this entry are closed }

By default, only the forum name / title is displayed in the <title></title> tag of the homepage of your vBulletin forum, which is far from ideal in terms of SEO. One should give a much more descriptive title to the home page of the forum other than the mere name of it.

To do this:

  1. Log in to the /admincp of your vBulletin forum
  2. From the left administrative menu, Styles & Templates –> Style Manager –> Select Edit Templates in the right drop down of the current style set.
  3. In the left selection of templates, double click Forum Home Templates –> double click FORUMHOME.
  4. Now opens the homepage template of your forum, search for ‘<title>’ and you would find the HTML tag to edit.
  5. Add something descriptive and keywords-rich in the <title></title> tag and click Save.
  6. Done!

vBulletin is such a sophisticated application with a very large user base. Took me some time to find this solution. Hope it helps! Check out how I changed the homepage title of the forum for Go.

{ Comments on this entry are closed }

MySQL Performance Tips

by Yang Yang on March 12, 2011

MySQLI’m not an expert but I’ve had my own errors and trials along the way so here I am. These are all the tips I believe you should use when you are optimizing for MySQL database performance. Some stuff may be very handy, but they may not be good for performance.

Design

  1. Normalize first, and de-normalize where appropriate. Table joins are never lags in performance. Use them!
  2. Choose the appropriate collation / charset. UTF16 is omnipotent but it requires 2 times the storage. UTF8 delivers more characters but it’s slower than latin1. Unless it’s necessary, use latin1.
  3. utf8_general_ci is slightly faster than utf8_unicode_ci, thus better in performance.
  4. Use NOT NULL wherever possible.
  5. Use indexes. Create indexes by analyzing the SELECTs you are doing on the table.
  6. Indexing increases performance in selecting, yet decreases performance in inserting. So don’t index everything but only those necessary. And don’t make duplicate indexes.

Querying

  1. Use smallest data types possible.
  2. IN (…) is a total fail. Avoid it wherever possible.
  3. ORDER BY RAND() is a fail too.
  4. When you need to SELECT … to make sure there’s no duplicate unique index values before inserting something, use INSERT … ON DUPLICATE KEY UPDATE … instead.
  5. If your app writes a lot, use InnoDB; if it reads a lot, use MyISAM. Here’s a comparison.
  6. Never use LIMIT xxxx1, xxxx2 with large tables especially when offset xxxx1 is a pretty large number. Instead, give a more strict WHERE … clause with LIMIT xxxx2.
  7. If a feature is deprecated, stop using it.
  8. Avoid wildcards % or _ at the beginning of LIKE queries, e.g. LIKE ‘%bloom’ – this should be avoided. For instance, you should store email addresses reversed (REVERSED()) so it’s faster to search by domain.
  9. If you have a large set of data rows to be inserted at once, create a combined INSERT query string in PHP first – that is, to bulk insert them in batches rather than one by one. LOAD DATA is also a better option than individual INSERT.
  10. Prefer GROUP BY over DISTINCT.
  11. Frequently visit Slow Query Log.
  12. Avoid calculated values in WHERE … , LIMIT … , ORDER BY … , etc.
  13. Use EXPLAIN … to get an idea of how MySQL is doing with your queries thus better optimize it. For example, it would suggest the indexes you should have created.
  14. Don’t SELECT * … on everything, SELECT only what you need.
  15. Be wary of lots of small queries that may be triggered in loops. Instead, combine them and use one large query wherever possible.

Storage Engines

  1. Know the pros and cons of different storage engines and use them accordingly. But try them out in the test environment before making the decision.
  2. Archive old data such as logs in ARCHIVE tables or MERGE tables.
  3. BLACKHOLE engine is very fast for busy things like logs.

my.ini

  1. Increase the default key buffer size: key_buffer = 128M
  2. Increase the default number of tables that can be kept open: table_cache = 128
  3. Increase the default sort buffer size:
    sort_buffer_size = 32M
    myisam_sort_buffer_size = 32M
  4. Disable binary logging that is for data replication by commenting out the line like this:  # log-bin=mysql-bin

What to read from here:

  1. Indexing: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html
  2. “LIMIT” Optimization: http://dev.mysql.com/doc/refman/5.0/en/limit-optimization.html
  3. “ORDER BY” Optimizationhttp://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html
  4. Efficient Paging: http://www.slideshare.net/suratbhati/efficient-pagination-using-mysql-6187107
  5. Configuration Tweaks: http://docs.cellblue.nl/2007/03/17/easy-mysql-performance-tweaks/

{ Comments on this entry are closed }

phpMyAdmin doesn’t show the exact size in MB when the size of your database exceeds 1GB. It just shows something like 4.2GB, truncating everything out in the 100MB precision. So is it possible to get the database size in MB in exact numbers using MySQL query?

Yes, it is:

SELECT CONCAT(sum(ROUND(((DATA_LENGTH + INDEX_LENGTH - DATA_FREE) / 1024 / 1024),2))," MB") AS Size FROM INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA like 'YOUR_DATABASE_NAME_HERE%' ;

Just change YOUR_DATABASE_NAME_HERE into the name of your database. And it would prints out something like this:

+------------+
| Size       |
+------------+
| 4906.79 MB |
+------------+
1 row in set (0.05 sec)

You can also get the size of a specific table. Read here: http://www.novell.com/communities/node/8706/check-mysql-database-size-using-sql-query

{ Comments on this entry are closed }

Pure CSS Rounded Corner, No Images

by Yang Yang on March 4, 2011

Though it does look great, I haven’t given it a try until the other day when I was developing smartbabynames.com. Notice the previous and next link immediately below the boy image at here:

http://www.smartbabynames.com/meaning/boy/Langleigh/

They look and feel great.

So here’s what I’ve done to achieve the rounded corner box in pure CSS – no images nor whatever. Just CSS:

.rounded {
	-moz-border-radius: 2px;
	-webkit-border-radius: 2px;
	-khtml-border-radius: 2px;
	border-radius: 2px;
}

Tested across major modern browsers other than IE. Sure it doesn’t work in IE6, but not sure if it works in IE7, IE8, IE9, etc. But let me know if you know.

{ Comments on this entry are closed }

ASCII is the most fundamental character set that has been around since the early days of command line interfaces. There are 128 (0 – 127) most basic ASCII characters such as a-z, A-Z, 0-9, and all the printable punctuations you can type out by a single strike of your keyboard.

As all ASCII characters have an internal decimal value of 0 – 127, which is 0x00 – 0x0F in heximal values, you can find all the non-ASCII characters in my_column by query:

SELECT * FROM my_table WHERE NOT HEX(my_column) REGEXP '^([0-7][0-9A-F])*$';

On the other hand, if you wish to find all records that a certain column (my_column) contains ASCII characters:

SELECT * FROM my_table WHERE HEX(my_column) REGEXP '^([0-7][0-9A-F])*$';

{ Comments on this entry are closed }