Thursday, November 26, 2009

Creating the iPhone Unlock Screen in xHTML, CSS and jQuery

The iPhone unlock screen in xHTML, CSS and jQuery

The iPhone: Everybody knows what it is, many people "played around" with the gadget and most people love it. I also own one of these amazing smartphones, and the looks of the software is really, really sleek and innovative (Just like we're used from Apple).

I wanted to transfer (some) of these amazing designs to a webpage to re-create the same look and feel for web browsers. Today, I'm going to show you how to create The iPhone unlock screen in xHTML, CSS and jQuery.



The iPhone unlock screen in xHTML, CSS and jQuery

OK, maybe not fully the "feeling" (look and feel) from the iPhone, since I can't make any webbrowser react to placing your finger on the screen, but your mouse will do the trick.

Features:

  • XHTML and CSS valid.
  • "Timer" displays the current time (Just like the iPhone).
  • "Date" displays the current date (Just like the iPhone).
  • Pretty sleek interface, including see-through elements (Just like the iPhone).
  • Changeable background.
  • Tested and working on Firefox 3, Internet Explorer 7 and Safari 3.

Known issues

  • The "slider" doesn't slide back (what the iPhone does).
  • The "unlock animation" isn't exactly the same as the iPhone.
  • Doesn't work on an actual iPhone.

Other than those minor issues, it works as expected. Want to know how I created it? Check it out.

Resources

Before I started, I needed some reference material to work with.

  • For the beautiful background image, I took a wallpaper from SocWall.
  • For the high resolution iPhone layout, Teehan+lax helpt me out.
  • I wanted to use the Slider component from jQuery UI.
  • I wanted to use jQuery for the functionality. The last version (v. 1.3.0) isn't compatible (yet) with the slider component, and therefor I'm using v. 1.2.6.
  • Using the jQuery slider component was pretty hard, Ryan helped me out a lot here.
  • To display the current date and time with JavaScript, I used WebDevelopersNotes as a resource.

With all resources set, on to the next step.


The xHTML

When you look in the source of the page, you'll see that the xHTML used isn't very complex.




08:23


Wednesday, July 6




 











  • #iphone-scrollcontainer will be the overall container that holds all other elements.
  • #iphone-inside will have the same width & height as the container, but will be used to place the background image that'll fade out.
  • #unlock-top is used for the top of the unlock screen, holding the time and date.
  • #timepicker & &datepicker; will be used to change into the current time and date.
  • #unlock-spacer is needed to push the bottom down.
  • #unlock-bottom is the place for the bottom.
  • #unlock-slider-wrapper is the container for the slider.
  • #unlock-slider is the place where the handle can slide, used by the jQuery slider.
  • #unlock-handle needed by the jQuery slider component: The actual handle for the slider.
The CSS

Now for the CSS part. We're going to use absolute positioning for this since the iPhone container will not resize. I'm only going to explain some things (not all) of the CSS file.

#iphone-scrollcontainer {    
height:461px;
width:320px;
position:absolute;
top:140px;
left:40px;
background-color:#000000;
}

#iphone-inside {
height:100%;
width:100%;
background-image:url(../images/background.png);

}

#unlock-spacer {
height:272px;
}
  • #iphone-scrollcontainer has a size of 461 by 320 px. It is asbsolute positioned from the top left corner of the page, moved 140px down and 40 px to the right. The container has a black (#000000) background color.
  • #iphone-inside holds the backround image (background.png). The reason why this isn't placed in the scollcontainer, is because the inside will be faded out by jQuery and the black background from the scrollcontainer will remain.
  • #unlock-spacer has a height of 272px, because the total height is 461px. From this total height, the top (95px) and the bottom (94px) needs to be substracted, leaving 272px for the spacer.
The JavaScript

At this point, we already have a pretty nice interface. For some interaction, we'll need to add some JavaScript. Like I said, I used the 1.2.6 version of jQuery to stay compatible with the Slider component. After including jquery-1.2.6.min.js, ui.core-1.5.3.js and ui.slider.js I created a new file called iphone-unlock.js with the following (Not the complete code):

$(document).ready(function() 
{
// Set the slider to be sliding
$("#unlock-slider").slider({
handle: "#unlock-handle",
animate:true,
stop: function(e,ui)
{
if($("#unlock-handle").position().left == 205)
{
unlock();
}
else
{
// Should slide back, but can't create it
// Reason: When calling "$("#unlock-slider").slider("moveTo", 0);"
// a loop is created, causing to crash the page
}
}});

var unlock = function()
{
$("#unlock-bottom").fadeOut("normal", function(){
$("#unlock-top").slideUp("fast", function(){
$("#iphone-inside").fadeOut("slow", function(){
window.location="index.html";
});
});
});
}
});
  • handle: tells the Slider component that the node is used as the handle.
  • animate: is set to true so when users click in the slider, it'll smootly animate to that position.
  • stop: is the function that's called when the slider stops. At that point, the slider checks if it's on his end (205px from the left). If so, it unlocks. If not, ht should slide back, but I can't create this effect (See the comments). If anyone knows a work-around for this, please let me know.
  • unlock function first fadeOuts the bottom, afster that it slides up the top and last it fades out the background image. Than it re-directs to another page, but in this case it's the same page.
All other code should be self-explanatory.

Conclusion and Download

Looking back, I think this is one pretty cool way of using the jQuery framework. With the sleek interface of the iPhone, what's not to like? Although not exactly everything is the same as the gadget, it still manages to get the iPhone feeling in your webbrowser.

That's it! Hoped you learned something new today and start loving the jQuery framework (like I do). Be prepared to expect more jQuery / CSS / xHTML iPhone UI articles in the future.

Update

Martin provided a fix for the "not sliding back". He also made some adjustments to the code to make it look more like an actual iPhone, like the glowing slider and the same effect.


--
ఇట్లు మీ,
చంద్రశేఖర్.

CubeCart 3.0 Installation and Configuration

CubeCart 3.0 Installation and Configuration

E-commerce applications come in all shapes and sizes, ranging from storefront solutions that generate Web pages, to bolt-on shopping carts that can be added to existing sites with product listings. There is also a wide range of costs, ranging from completely free to completely overpriced. For Web developers who wish to modify an e-commerce application for a client, there is also a range of code availability, ranging from entirely open source to entirely locked down (typically using some sort of PHP encoder).

In this tutorial, we will get an introduction to CubeCart, created and distributed by Devellion Limited. Their flagship product is one of the easiest low-cost e-commerce solutions available, and is growing in popularity. Note that CubeCart is not technically open source, since the code cannot be freely redistributed. On the other hand, most of the code is not protected using encoding, and can thus be read and understood.

CubeCart utilizes PHP, XHTML, and CSS — thankfully using divs for page layout, and not HTML tables, as still done by some major shopping carts. The pages are built using templates, making it easier for developers and third-party vendors to create custom themes for the pages (known as "skins"). Version 3.0 offers product listings, options, categories, and images, including an image gallery. It also offers customer shopping cart functionality, order history, e-mail and print invoicing, multiple currencies, popular shipping and payment options, e-mail marketing, support for digital products, tell-a-friend links, product search, prebuilt skins, site documents, and a straightforward administrative panel, which we will explore later in this tutorial.

In this tutorial, we will consider the different versions available, and their licensing options, as well as how to install and configure it.

System Requirements

To run CubeCart, you will need several components: a Web server, a MySQL database, the PHP scripting language, and either Zend Optimizer or ionCube PHP Encoder, for decoding protected files. All of these components should be installed and verified to work, before installing CubeCart itself. Most competent Web hosting services provide all of these needed components.

For this tutorial, we will be utilizing Apache version 2.2.8, MySQL 5.0, and PHP 5.2.5. But CubeCart will work fine with many of the earlier versions of these components. If you are setting up a development environment on a Windows server, then detailed information can be found at DeveloperTutorials.com, with instructions on how to install and configure Apache, MySQL, and PHP.

cURL with SSL support is required for some shipping and payment modules. The GD image library is recommended, for product image manipulation.

Choosing and Downloading CubeCart

On the CubeCart homepage, you will see that two major versions are currently available, version 3 and the recently released version 4.

The former version is completely free as long as you leave the company's copyright notice on your site's pages. The notice can be removed by purchasing a copyright removal key for a one-time fee of $89.95. The latest version has the same pricing, except the software license is no longer free, but instead $129.95. There is a 30-day free trial if you would like to test that version risk-free. (All product information is as of this writing, and could change in the future.)

Even though version 4 of CubeCart adds many new features, this tutorial will focus on version 3, because that is the one most commonly used at this time, and thus most thoroughly tested by the vendor and by users worldwide. In addition, there are far more modules written and tested for version 3.

   

Installing CubeCart


Your first step in installing CubeCart is to go to the version 3 download page.

Click the link for version 3.0.17, which is what we will be using in this tutorial. This will take you to the 3.0.17 page, which has more detailed information about this particular maintenance release.

Click the Download button, and save the archive file (CubeCart_3.0.17.zip) somewhere on your computer. If you have a broadband connection to the Internet, then the download process should take just a few seconds, because the installation file is only 2.5 megabytes in size. (Before leaving that download page, you may notice that the total number of downloads so far exceeds 200,000. For version 3.0.15, the figure is greater than 7 million! This gives you an idea as to CubeCart's popularity.)

Open up the archive file, and save the contents of the "upload" directory into a new CubeCart directory within your Web server's root. The entire CubeCart installation on disk comprises 1125 files in 236 directories.

Next create a database on your MySQL server for CubeCart. The following commands will do this:

CREATE DATABASE cubecart_test;
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE,
DROP, INDEX, ALTER, CREATE TEMPORARY TABLES,
LOCK TABLES ON cubecart_test.* TO cubecart_user@localhost
IDENTIFIED BY 'password;

Note that we are using test values only, and you should use a far more secure password for any production installation.

Point your Web browser to the CubeCart index.php, which will begin CubeCart's installation process. For instance, if you had named the CubeCart root directory "CubeCart/" and had placed it in the root directory of your local Web server, then the URL to use would be "http://localhost/CubeCart/index.php". You can even leave off the "index.php" if your Web server has been configured to look for that file name as a default.

At the license agreement page, click the agreement checkbox and then the Continue button.

At the second screen, verify that all of the file permissions are set correctly. This applies only to Linux and Unix servers, as seen in the screenshot above, in which a Windows XP server is being used.

The third screen, shown above, is a critical one, because this is where you will enter the information needed by CubeCart to connect to the database you had created earlier. You should also set your country location and your administrative login information. CubeCart version 3.x comes preloaded with three skins: Classic, Legend, and Killer. In this tutorial, we will use the first option, which is the default. You can click on any of the three thumbnails to see a larger image of each skin. Most likely, none of the advanced settings need to be changed.

At this point you can breathe a sigh of relief, because you are now past the stage of the installation process that gives beginners the most difficulties. If you are installing on a Linux or Unix server, you are now prompted to change the permissions of the configuration file includes/global.inc.php, making it not writable by others, for security reasons. Again, for Windows users, this is not applicable. (However, it does not stop the admin panel of CubeCart version 3.0.16 from complaining that your configuration file is still writable, whenever you log in as the administrator.)

You have now finished CubeCart's installation process.

Verifying Your Installation

If you now try to run CubeCart by going to the root directory of your store, you will receive the error message "WARNING - Your store will not function until the install directory and/or upgrade.php is deleted from the server." Delete or rename the directory "install", and then reload the page.

You should now see the initial CubeCart store homepage, shown in the screenshot above. By default, the left-hand column contains boxes for categories, featured products, product information, currencies, and languages. The right-hand column shows the customer's current shopping basket, the most popular products, products on sale, and a newsletter subscription form. The central area has a welcome message and a product list, which initially only includes a test product.

Clicking on the "Test Category" link takes you to a page showing all of the products in that category — again, just a single one at this point.


Configuring CubeCart

To access the admin panel, simply append the word "admin" after the CubeCart root directory path. Continuing our example mentioned earlier, the URL would be http://localhost/CubeCart/admin/index.php

Login using the CubeCart administrator username and password that you specified in the third stage of the installation process.

The main section used for changing your store settings, is appropriately named "General Settings", and is found in the "Store Config" menu area in the left-hand column.

Do not be intimidated by the fairly large number of options on this page, because most of them will never need to be changed. However, you should customize all of the information in the "Meta Data" section at the top.

Confirm that the values in the "Locale Settings" section, near the bottom of the page, are correct. The other three menu items in the "Store Config" menu area can be used for: working with countries and the zones and states within them; tax rates that you wish applied to customers residing in those areas; and currencies that customers can view your products priced in, and at what foreign exchange rates.

Lastly, go to the "Site Documents" link in the "Documents" menu area in the left-hand column.

Edit the contents of, or simply delete, the four default site documents: About Us, Contact Us, Privacy Policy, and Terms & Conditions.

If and when you wish to deploy your CubeCart store on the Web, upload all of the contents of the CubeCart directory into the root directory of your remote server. Then export the CubeCart database on your local computer into an SQL file, and import that into your remote MySQL server. Next, modify the site settings within "includes/global.inc.php" if needed. Finally, test the CubeCart store as well as the admin panel, to verify that everything is working.

You now have a fully functioning online store, ready for products to be added.


--
ఇట్లు మీ,
చంద్రశేఖర్.

Practical PHP Performance

Introduction

When it comes to building web applications in PHP, performance isn't typically a major concern. Features, usability and any business concerns are considered a greater priority, as they can be better demonstrated and visualised. Performance graphs don't make the boss's day.

So, why should you as a PHP developer, worry about performance? Quite a few reasons, in fact:

   1. Efficient code gives you more flexibility with what you do with your application - for example, you can't exactly throw in a thumbnailing routine if you've already maxxed your server.
   2. Performance techniques generally line up with best practices, and while best practices are their own justification, they will save you time (and money!) in the long run.
   3. On a high-scale application, performance graphs won't make much of a difference. Still, informing the boss that, thanks to your performance efforts, you can cut server costs significantly, will definitely earn you some credit, and maybe even a raise.
   4. Well written (and therefore efficient) are easier to debug.

The potential performance of PHP applications is certainly something to be proud of - at one stage, Digg was handling 200 million page views per month with just three web servers and eight database servers. PHP by its nature is one of the fastest web scripting languages available, having been more or less written for mod_php, the Apache module used for most PHP installations. Unlike Java, PHP is sufficiently dynamic to run literally as lightweight as you require - for example, you could write a web service in just ten lines of code that could easily handle millions of hits a day, as opposed to the overhead of pulling in a significant chunk of enterprise-sized libraries that you probably don't need.

Performance: is it really what you're after?

Of course, when any performance considerations come up, it is worth considering if you really want to aggresively manage PHP performance. A common misunderstanding is the difference between performance and scalability. Performance generally refers to the raw efficiency of the application, whereas scalability is the application's ability to handle greater loads.

As you move into high-traffic web applications, especially the large scale installations of big business, it is common to find that performance is not a concern as the business can afford to simply add another server when needed. Still, keeping performance in mind while developing an application can create significant benefits further down the line.

Ten ways to improve your application's performance

So, without further ado, here are ten ways you can improve the performance of your web applications.
1. Start with the tools

You can't analyze the performance of your entire application yourself. You won't be watching every single line of code executed. Find software that helps you profile your applications effectively; I find PhpED's integrated profiler just works, and is great for telling me where script execution is being held up. There are quite a few good tools available, however, especially for non-Windows platforms. A benchmarking tool - such as ab - may also help, as well as a good debugger. A good set of tools will help you identify problems and deal with them for more effective performance optimization.
2. Cache, cache, cache!

For some applications, caching your HTML is the most effective performance optimization. Have you got static content on your site, but find you needlessly regenerate it on every page load? Executing your script could take 5 seconds. Sending over a cache file of the output would take more like 0.005 seconds. Consider taking the entire output of your script, caching it in a simple HTML file and serving it on subsequent requests based on its file modification timestamp. Here's a simple way to achieve it:

<?php
if (!file_exists('cache.html') ||
     filemtime('cache.html') < (time()-$timeout)) {
 $output = execute_some_complex_function();
 file_put_contents('cache.html', $output);
 echo $output;
} else {
 echo file_get_contents('cache.html');
}

3. Fundamentals: code

As with anything, your fundamental code is the end of the line for performance, but is often a great place to start as well. While this is more effective when considered during development, a performance optimisation effort focusing solely on code can deliver significant results. Look for obvious issues such as function calls in for() loops, like this:

<?php
for($i=0;$i<count($some_array);$i++)
{
 // ...
}

In this example, count($some_array) is executed every iteration of the for loop. So, if you're looping twenty times, you'll make twenty calls to the function. If your array is rather large, this can create some pretty big performance issues.

Next, work on general techniques. Error suppresion (with @) is expensive, as are error messages (and associated error handling). Initialise variables locally (working on global variables or object properties is much slower than local variables). Use single quotes for strings. Sticfk to language constructs where available - echo is a construct, print() is a function -- and with it, all the overhead of a function. Try this blog post by Reinbold Weber for some more suggestions.
4. Structure

If you take a look at the more general aspects of your application, chances are there are structural changes you can make for significant benefits. For example, are you using four objects when you could be using three? Are you using seperate files for presentation logic when you really only need one? Are your users being redirected around your application, with multiple resource-intensive requests, when you could get them straight to the point?

Your code also represents a number of structural decisions that may have scope for improvement. For example, a single lengthy switch statement instead of complex action handlers and multiple if-elseif-else statements can yield considerably performance benefits. Of course, don't start getting rid of all your OOP and complex routines in favour of procedural hacks - the development time saved by good development practices far outweighs server costs.
5. Bottlenecks

When profiling your application, chances are you'll spot some obvious bottlenecks. For example, are you going to disk ten times in your application, and finding your CPU lounges about as your hard disk responds? Interestingly, your disk operations could be the most time consuming areas of your entire script. Watch memory usage as well - if you go over available memory, you'll start going into virtual memory instead, which is generally stored in a file on disk and is infinitely slower than operations on RAM. You may find creating a virtual hard disk that is stored in RAM gives you the benefits of a filesystem combined with (most of) the speed of memory.
6. PHP: Use it!

The number of PHP developers rewriting functionality already available in the PHP core. Take this, for example:

<?php
$string = file_get_contents("somefile.txt");
$last_split = 0;
for ($i=0;$i<strlen($string);$i++)
{
  if ($string[$i] == "\n") {
    $array[] = substr($string, $last_split, $i);
    $last_split = $i;
  }
}

(This is a real code snippet, from a project I worked on some years back)

Three things to notice here. First, the developer has conveniently forgotten the explode() function. Second, the developer is iterating over every single character of somefile.txt. Third, if somefile.txt is twenty thousand characters long, strlen() is being called 20,000 times. The reason to use the PHP core functions is that they are written in C and interface with the variables passed to them directly. Writing your own functionality in PHP is much slower, as your PHP code itself has to be interpreted, and has to go through the layer of PHP when handling variables. There was also a lot of code to deal with the actual content of each line in this snippet, where the developer should have been using array_walk() or array_map().
7. Use cron and CLI

If you've ever tried to do anything in bulk, do complex calculations (such as resizing images) on the fly, or conduct batch operations, you probably want to be using crontab and CLI scripts. If you want to resize images for thumbs on your website, use crontab to run a PHP-CLI script that does the resizing every fifteen minutes, and show a "PREVIEW COMING SOON" image in its place in the meantime. Unless the image is crucial, your users will live. Use consistent file naming to store the resized images (or whatever else you're processign) and if_file_exists() to check if it's been done yet at the frontend.

As crontab is a task scheduler (in fact, the Windows alternative is literally titled "Scheduled Tasks"), it's well suited for applications that can/should be performed regularly. The idea of using cron and CLI is that batch processing tasks can be queued up in a job queue that is stored seperately from the web application, and a CLI script can come along and work through the job queue, typically at a rate faster than the job queue fills up. If you have ten images to be resized, you can fill up a database table titled job_queue with a list of filenames of the original images and the intended dimensions. Entries can be added to the queue on the fly, and as needed.

The resizing script, which may even be on a seperate server, can resize all the images and place them in predefined locations. The web application frontend can entirely independently check if the resized image exists. If it does not, a "image resize in progress" thumbnail can be displayed. In this way, the web application does not keep the user waiting, can get on with the task of serving web pages and is reasonably efficient. (It also saves complex process forking, which can be very messy.)
8. Outsource the hard work

Of course, if you're really doing something in bulk - such as scraping entire websites - see if you can have another server do the job entirely. If possible, find a public (either commercial or non-commercial) API that can do the job for you. If this isn't an option, setup a seperate server dedicated for your complex processing tasks and talk to it via SOAP, XML-RPC or similar. You probably don't want your web facing server tackling challenging computation tasks the day your site is dugg or slashdotted and its traffic shoots through the roof.

Typical tasks that can be handled by external third-party APIs include term extraction (with Yahoo, for example), content verification, spam checking (with Akismet, for example) and other information or content related tasks. However, APIs can also be used to source data.
9. Compression

Depending on the nature of the content you're serving, you may be able to find general performance benefits from compression. If bandwidth or load times are an issue, turning on Apache's mod_deflate and/or mod_gzip will save you a lot of bandwidth, but will create slightly more CPU usage (for the compression algorithm). This requires no PHP at all and on some sites can deliver massive bandwidth savings, translating to saved bandwidth costs (which can be used to fund additional servers instead, or to give you a raise!).

Remember that this is designed for large file transfers - for example, you might be an image or file hosting site, or at least have such a feature within your application for your general user base. Some images and files can compress very well, and the CPU overhead of compressing a file is typically worthwhile, especially given the additional CPU cycles required to continue serving a large file. However, it is a trade-off, and if CPU usage is of major concern to you, you should consider the pros and cons, and possibly run benchmarks, to ascertain the potential benefits before enabling compression.
10. Look around

The world of PHP script performance is always changing. People conduct research, and then post their findings online. For example, this article by John Lim touches upon an interesting point of scalability against speed. Watch the PHP news sites, and the IT news sites in general, for success stories in optimizing PHP sites. Also look at the big guys; the major corporate PHP users often pass on their success stories through their blogs and developer portals; both Facebook and Yahoo have done so in the past.

Conclusion

Optimizing PHP scripts is clearly a very abstract topic. Different strategies work for different situations, and while not all are effective, with these ten tips you can easily improve the performance of your web applications. Keep researching; if performance is an issue, try experimenting as well. Facebook often used a change, benchmark, change, benchmark process where they would make a performance tweak and measure its effectiveness -- a great way to learn about optimizing PHP. Good luck!


--
ఇట్లు మీ,
చంద్రశేఖర్.

Easy PDF Generation in PHP

Introduction

PDF is a popular, versatile format for storing content. PDF files can be generated once, and distributed in peace knowing that they will look the same across all platforms. They also serve as a perfect way of allowing your users to download or email a page from your website. In this tutorial, I'll show you how to generate PDF files in pure PHP and distribute your content in a single, consistent format.

Ever wanted to generate PDF files in your web application? You could let your users download pages in PDF format, generate PDF reports to be distributed in your organisation, or just get better control over how your pages look when printed. In this PHP PDF tutorial, we'll work through building a simple page and saving it as a PDF file.

We'll be using the FPDF library to generate our PDF files. The library is a simple PHP class that provides some very complex PDF generation functionality. Luckily, it offers some high level methods that you can use to quickly and easily generate PDF files without having to understand the internals of the PDF format.

Why would you want to generate PDFs?

When it comes to data output (not interface, output), web applications face an inherent problem: complex format and structures are very unreliable. For your complex reporting interfaces, you are faced with browser compatibility challenges, screen width issues and font size uncertainty. When it comes to demoing your latest version to your client, you may often find yourself embarassed by unforseen environment issues, and it's hard to tell a client their computer is broken.

At the same time, distributing reports - or any content, for that matter - from your web applications is also tricky. Users can try the "Save As" or "Save Page As" function in their browser, which will then attempt to calculate all the file dependencies and create an independent copy of the current page. Users will often distribute only the HTML page, losing all the CSS files and images - and with it, all hope of the end user viewing your data.

PDF as a format solves these problems wonderfully. When it comes to laying out a PDF document, you can simply assume it will look the same on your system as on the end user's. Screen resolution differences? Adobe Reader will scale beautifully. Images? SVG them and you'll have no problems; photographic data can cleanly resize. Browser versions? As long as they're all using Adobe Reader, or a reasonable alternative (such as Foxit Reader), you're fine.

Think of it like web design in a world where everyone uses Firefox.

Options for PDF Generation
In this article, we'll take a look at FPDF. However, you may have noticed a section in the PHP manual itself with PDF functions. A brief look at php.net/pdf reveals a PDFLib-based PECL extension that has not been updated in nearly six months. PDFLib itself is not free, however, and PDFLib Lite is not terribly effective. You also need access to the server to install the extension, which isn't always possible on a shared host.

There is a special section in the PHP manual on this - take a look at this FAQ entry. The two main free alternatives to FPDF are the R&OS PDF Class and phppdflib, but neither have been updated in a few years. There's also the Zend_PDF component of the Zend Framework, although it isn't very mature - still worth a look if you use the Zend Framework, however. In this time, FPDF has become the de facto standard for PDF generation in PHP. Other options exist - such as using COM to communicate with an existing Windows application with PDF export functionality - however none are as reliable and flexible as FPDF. In this tutorial, we'll be using FPDF exclusively, but the alternatives are definitely worth a look, especially their source code.


Hello World with FPDF

Let's get started with some basic PDF generation using FPDF. Load up your code editor and bash out the following:

    <?php
    require('fpdf.php');
    $PDF = new FPDF();

    $PDF->AddPage();
    $PDF->SetFont('Arial', 'B', 16);
    $PDF->Cell(40, 10, 'Hello World!');

    $PDF->Output();

    I'll explain what all this does in a moment. For now, grab the latest version of FPDF from fpdf.org, extract it to somewhere in your web server's document root and save this snippet in a PHP file under the same folder as fpdf.php. Load it up in your web browser and you should see something like this:

    Nothing special, but we're on our way to PDF glory!


    Examining the code


    Let's take a look through that Hello World! snippet we just wrote.

        <?php
        require('fpdf.php');
        $PDF = new FPDF();

        $PDF->AddPage();
        $PDF->SetFont('Arial', 'B', 16);
        $PDF->Cell(40, 10, 'Hello World!');

        $PDF->Output();

    Barring the output, this is pretty standard stuff. Here's a quick rundown.


    We start by including the FPDF library with the require('fpdf.php') line. FPDF is pure PHP: that is, no PECL extension is required. It's a little slower than PDFLib and CPDFLib, but it's infinitely more portable and much easier to use.

    We create a new instance of the FPDF class in $PDF. Typically, for each PDF document you want to work with (each document can have multiple pages), you'll want to use a new object. Chances are, however, that you'll only ever need one.

    This is where we launch into the actual PDF construction. We first need to create a page. That's right - you can have a PDF document with no pages. If you omit the AddPage() call and the subsequent two lines, then try it in your browser, Adobe Reader will display a blank empty page, but there really isn't one. As an example, let's take a look at what the library outputs without any pages, fonts or text cells created:

        %PDF-1.3

        3 0 obj

        <</Type /Page

        /Parent 1 0 R

        /Resources 2 0 R

        /Contents 4 0 R>>

        endobj

        4 0 obj

        <</Filter /FlateDecode /Length 19>>

        stream

        x�3R��2�35W(�

    Nothing terribly spectacular, especially consider its an empty document. However, this is a barebones PDF document, and while you may never have to actually work with this, it's important to be aware of what's happening. As this is all purely text, all the Output() method (which we'll examine in a moment) does is send a HTTP header of application/pdf and print this data to the page.

    But back to our code. Here's the bulk of our PDF:

        $PDF->AddPage();
        $PDF->SetFont('Arial', 'I', 14);
        $PDF->Cell(40, 10, 'Hello World!');

    This tells FPDF to first create a page within our PDF document (it works with an internal copy while constructing your PDF), then set the font currently in use to italicised Arial at 14pt. If you don't set a font, it will default to no font and your text will not display as part of the PDF.

    Finally, we create a text cell on the page, with a width of 40 and height of 10, and write the text 'Hello World!' in it. The Cell() method is the workhorse of the FPDF library. A cell is a rectangular area with optional borders, background colour and character string. Whenever you want to print text to your PDF file, chances are you'll be using the Cell() method. The method has eight arguments, even though we've only supplied three here. The others include a border option, text alignment, transparent or filled background and URL - read this manual page on the Cell method for further information.

    The Output() method is especially interesting. By default it will output the PDF file as the current web page (or shell), but it can also save your newly generated PDF file to disk. To save to disk, for example, we would call the method with $PDF->Output('output.pdf', 'F'). In the first argument, we specify the file name to output (typically relative to the directory of the current script, not the FPDF library file). In the second, we specify 'F' for File, to save to a local file. Other options include sending inline to the browser (default), forcing the browser to download the file, or even simply returning the document data as a string. See this manual page for more details on the options available.


    Further reading on FPDF

    In this tutorial, we've put together a basic PDF file with nothing but a line of text in it. However, FPDF is capable of far more. The library has a lot of complex yet high level functionality available - you can work with headers and footers, easily handle page breaks, insert images, use multiple columns and tables, and even insert hyperlinked text.

    The fpdf.org website has an excellent collection of tutorials; head over to the FPDF tutorial page and have a browse through. You'll notice that the tutorials use OOP to construct pages, defining a class that extends the core FPDF class. The library is very flexible, and works just as you'd expect any normal PHP class to - and this is where its strength lies. Experiment with the library as you read through the tutorials, and you will quickly find how easy it is to create detailed PDF files in PHP.

Thanks
B.chandrashekhar

Sorting an Array in PHP

Now and then you need to sort your arrays alphabetically or numerically, if nothing else, then just to apply some programming logic and attain the desired output. You can sort an array in PHP by using two functions: sort(), to sort an array in ascending order, and rsort(), to sort an array in the reverse order, or descending order. I'll illustrate this function with an example.

First, we loop through an array without applying any sorting:

<?php

$narray[0]="Alfred";
$narray[1]="Robert";
$narray[2]="Deepak";
$narray[3]="Teresa";
$narray[4]="Joshua";
$narray[5]="Chandni";
$narray[6]="Sadiq";
$narray[7]="Vladimir";

for($i=0; $i<8; $i++)
{
print $narray[$i] . "<br />";
}

?>

The output of this PHP code is:

Alfred
Robert
Deepak
Teresa
Joshua
Chandni
Sadiq
Vladimir

Now we apply the sort() function and see what happens.

<?php

$narray[0]="Alfred";
$narray[1]="Robert";
$narray[2]="Deepak";
$narray[3]="Teresa";
$narray[4]="Joshua";
$narray[5]="Chandni";
$narray[6]="Sadiq";
$narray[7]="Vladimir";

sort($narray);

for($i=0; $i<8; $i++)
{
print $narray[$i] . "<br />";
}

?>

The output of this PHP code is:

Alfred
Chandni
Deepak
Joshua
Robert
Sadiq
Teresa
Vladimir

You can see that the names have been alphabetically sorted in the ascending order. To sort of the names in descending order, we change the program like this:

<?php

$narray[0]="Alfred";
$narray[1]="Robert";
$narray[2]="Deepak";
$narray[3]="Teresa";
$narray[4]="Joshua";
$narray[5]="Chandni";
$narray[6]="Sadiq";
$narray[7]="Vladimir";

rsort($narray);

for($i=0; $i<8; $i++)
{
print $narray[$i] . "<br />";
}

?>

Now the output is:

Vladimir
Teresa
Sadiq
Robert
Joshua
Deepak
Chandni
Alfred

A few days ago we studied about associative arrays in PHP. Now, you cannot sort an associative array by using the sort() function. Let's see what happens if you apply the sort() function on an associative array in PHP:

<?php

$narray["IBM"]="International Business Machines";
$narray["MS"]="Microsoft";
$narray["CA"]="Computer Associated";
$narray["WHO"]="World Health Organization";
$narray["UK"]="United Kingdon";
$narray["BA"]="Something Random";

sort($narray);

foreach($narray as $key => $value)
{
print $key . " = " . $value . "<br />";
}

?>

The outcome you get is:

0 = Computer Associated
1 = International Business Machines
2 = Microsoft
3 = Something Random
4 = United Kingdon
5 = World Health Organization

So you can see that if you apply the sort() function on an associative array, it is sorted by the numeric value of the index. To sort an associative array, you use the asort() function in the following manner:

<?php

$narray["IBM"]="International Business Machines";
$narray["MS"]="Microsoft";
$narray["CA"]="Computer Associated";
$narray["WHO"]="World Health Organization";
$narray["UK"]="United Kingdon";
$narray["BA"]="Something Random";
asort($narray);
foreach($narray as $key => $value)
{
print $key . " = " . $value . "<br />";
}

?>

The result is:

CA = Computer Associated
IBM = International Business Machines
MS = Microsoft
BA = Something Random
UK = United Kingdon
WHO = World Health Organization

As you can see, the array has been sorted in the ascending order by the value of the array, and not the string index value, or the key of the array. You can use arsort() to sort an associative array in the descending order.

To sort an associative array according to the key of the array, you can use the ksort() function in the following manner:

<?php

$narray["IBM"]="International Business Machines";
$narray["MS"]="Microsoft";
$narray["CA"]="Computer Associated";
$narray["WHO"]="World Health Organization";
$narray["UK"]="United Kingdon";
$narray["BA"]="Something Random";

ksort($narray);

foreach($narray as $key => $value)
{
print $key . " = " . $value . "<br />";
}

?>

Similarly, you can sort an associative array according to the key, in ascending order by using the krsort() function.



--
Thanks,
B.Chandrashekhar.

Monday, November 16, 2009

Myeclispe Plugins links

Installing FlexBuilder Eclipse Plug-in

To install the FlexBuilder Eclipse Plug-in version you will probably want to first uninstall the FlexBuilder Standalone. You will also need to download and install Eclipse. Important: Eclipse is currently in version 3.3.1.1 at the time of writing. If you're using FlexBuilder 3, good for you! Go and download the latest version (get the classic distro). However, FlexBuilder 2 does not work on Eclipse 3.3. You'll need to download the older version 3.1 or 3.2 of the SDK which are hidden deep in the dungeons of the Eclipse Project site.

After Eclipse is installed you can proceed with the installation of the FlexBuilder plug-in. Additional installation instructions can be found on the Adobe Site.

Installing Plug-ins

If you take a look at the Eclipse plugin central you're liable to notice two things right off the bat. First, there are a ridiculous number of plugins especially for really obscure branches of Java development. Second, the Eclipse site is completely ugly and it's often incredibly frustrating to use. I'll try to help you get to the juicy bits quickly.

By far the best way to install Eclipse plug-ins is to use update sites. Update sites allow you to select and download plug-in packages directly from the developer from within the Eclipse program. The update site URLs are notoriously difficult to find due to the Eclipse site's confusing navigation. For example, I jut tried to get to the update site URL for Europa, a major Eclipse supported plugin, and it took about 4 minutes worth of clicking for me to find it (at best it takes 3 clicks). These elusive links to update sites should, in my opinion, be in big red letters on the front of every project page so in case Eclipse is reading this right now, WTF doodz!?

Once you have the update site URL take the following steps to search the site for updates:

  1. Go into eclipse and click on Help > Software Updates > Find and Install… (Help menu? Again, WTF)
  2. Select Search for new features to install
  3. Click the next > button
  4. Click on the New remote site… button
  5. Give the update site a label and paste the update site url. Click ok
  6. Make sure the site you added (and any other sites you want to update) are checked and click the Finish button
  7. On the next screen you'll see you can choose which features of the plugin you would like to install. For most plugins, you'll probably want all of them so check the root folder. Note: you may see an error at the top of the window such as FooBar v.0.7 requires plug-in 'org.eclipse.foobar.core'. If this happens, it can usually be fixed by clicking on the Select Required button which will automatically select the required features.
  8. When you're done selecting features, click Next >
  9. ALWAYS CAREFULLY READ EVERY LINE OF THE EULA! then click I accept the terms of the license agreements and click Next >
  10. Click the Finish button. You may be asked again about certain features during installation for which you can click Install All to keep going
  11. When the installation is done, restart the Eclipse SDK

That's it in just 11 tedious steps!

To get updates of already installed plugins choose Search for updates of the currently installed features at step 2 and follow the instructions above. If you install a plugin that conflicts with your setup or if you want to temporarily disable or uninstall a plugin, you can always go to Help > Software Updates > Manage Configuration… to manage your environment. Keep in mind that most plugins add new items to Eclipse preferences, the Window > Open Perspective dialog, the Window > Show View dialog or the File > New dialog.

A note about simultaneous releases - Europa, Ganymede, and Callisto

In 2006 the Eclipse Foundation decided to take ten of the most used plug-ins and wrap them into one release so that the plug-ins would update at the same time as the Eclipse SDK. This project was called Callisto. They considered it a great success so they did it again in 2007 and (confusingly) called it Europa. 2008's project is called Ganymede.

Some of the plug-ins listed below are part of the Europa project (currently, the latest full version release). To install these plugins you will want to check the Europa update site which contains several projects but you should select only the ones you want to install.

Must-have Plug-ins

Plugin Web Tools Platform (WTP)
Website http://www.eclipse.org/webtools/
Update Site http://download.eclipse.org/releases/europa/site.xml
Description If you work with Flex or Flash, chances are you're making a website. This project provides tools for editing the standard web formats like XHTML.

Mylyn is part of the Europa simultaneous release.

Plugin Mylyn
Website http://www.eclipse.org/mylyn/
Update Site http://download.eclipse.org/releases/europa/site.xml
Description Mylyn lets you code using the concept of task-oriented development. It is built to help you focus on a single task by obscuring unused classes and hooking in with most of the commonly used bug-tracking tools. Especially cool if you use a program like TRAC.

Mylyn is part of the Europa simultaneous release.

Plugin CVS & ANT
Website N/A
Update Site N/A
Description Technically, not a plugin. CVS support and ANT support are built into the latest version of Eclipse so you won't need to install these separately. However, they function like plugins and they are very useful so I think they deserve a mention here.

CVS support allows you to manage CVS (Concurrent Versioning System) Repositories and make checkouts and changes from within Eclipse. Personally I prefer SVN for versioning (see also Subclipse) but sometimes it's not up to me and this functionality is quite useful.

ANT is a tool you can use to create build scripts for your Flex project or for any other language. This is a must-have for larger projects with complicated deploy folders. More info on using ANT and Flex can be found at Adobe Labs and in the Flex 2 docs.

Plugin Snippets
Website N/A
Update Site N/A
Description OK. To be honest, I'm not sure how you install this one. I think it's automatically installed as part of the Web Tools Project (WTP) or maybe PHP Development Tools (PDT) also mentioned in this post. Either way, once it's installed you can access it through the Window > Show View menu item.

Snippets lets you define code templates that let you add big chunks of code to a class with a few clicks. You can define variables that appear in the code as well. For example, you may create a snippet that creates a private variable and a public getter and setter and only pass in the variable name and the type. Pretty useful, but not as good as TextMate.

Plugin Subclipse
Website http://subclipse.tigris.org/
Update Site http://subclipse.tigris.org/update_1.2.x
Description A plugin that lets you manage a list of Subversion (SVN) repositories, check out directly from the list, and update, commit, etc. the files in the repository straight from your navigation view in Eclipse. So basically like Tortoise SVN for Eclipse.
Plugin TODO / FIXME Task Plugin
Website http://www.richinternet.de/blog/index.cfm?entry=911D4B57-0F0D-5A73-AF6F4D4D04099757
Update Site N/A - see website
Description This is a simple little tool that tracks all of your TODO or FIXME comments in Eclipse's Tasks view. There's no update site so you'll have to follow the instructions on the webpage.
Plugin JSEclipse
Website http://labs.adobe.com/technologies/jseclipse/
Update Site http://download.macromedia.com/pub/labs/jseclipse/autoinstall
Description Adobe's official JavaScript plugin for Eclipse with support for FlexBuilder, popular JS frameworks, and JavaDoc.

Notable Mention

Plugin Eclipse Regular Expression Tester
Website http://www.brosinski.com/regex/
Update Site http://brosinski.com/regex/update
Description This is a tool that will help you visualize Regular Expressions which can be very confounding to look at even for people who are experienced with using them.
Plugin Ruby Development Tools (RDT)
Website http://rubyeclipse.sourceforge.net/
Update Site http://updatesite.rubypeople.org/release
Description If you develop in Ruby, you'll probably want this. Also see PDT below.
Plugin PHP Development Tools (PDT)
Website http://www.eclipse.org/pdt/
Update Site http://download.eclipse.org/tools/pdt/updates/
Description If you develop in PHP, you'll probably want this. Also see RDT above.
Plugin Aptana
Website http://www.aptana.com/
Update Site http://update.aptana.com/update/3.2/
Description A full featured IDE for working on web apps. There is also a standalone version. Aptana looks very promising, however, I disabled it since it seemed to be conflicting with other plugins in my Eclipse setup.

Roger kinda likes it though:

aptana is great because it is an integrated development environment, unlike a standalone text editor. Its integrated Javascript contextual completion and compatibility matrices are lifesavers. It plays nicely with other eclipse editors and uses a plugin architecture to support not only [X]HTML and Javascript, but also RoR and PHP.

Plugin FDT 3.0
Website http://fdt.powerflasher.com/
Update Site N/A
Description FDT has a great track record and the Enterprise edition of FDT 3.0 could be the first third-party FlexBuilder competitor worth considering. However, with the price of the package now approaching the nine-hundred dollar mark thanks to our failing currency, this is a fairly high-risk alternative.
Plugin Eclipse Monkey (aka project dash)
Website http://www.eclipse.org/dash/
Update Site http://download.eclipse.org/technology/dash/update/
Description Allows you to create scripts to automate Eclipse itself using JS. I haven't used this but it sounds interesting.


--
Thanks,
B.Chandrashekhar.

Grant database to other hosts - mysql

select mysql database;

GRANT ALL PRIVILEGES ON *.* TO root@"%" IDENTIFIED BY 'jiva' WITH GRANT OPTION;



--
Thanks,
B.Chandrashekhar.

What’s New in MySQL 5.1

What's New in MySQL 5.1
Partitioning, Event scheduler are two big features that are introduced in this version.
and a major of sql optimization has been done.
MySQL 5.1 performs much better in all tests: it can handle more transactions per second and it does not deadlock with 256 threads, unlike 5.0.

The following features have been added to MySQL 5.1.

*

Partitioning. This capability enables distributing portions of individual tables across a file system, according to rules which can be set when the table is created. In effect, different portions of a table are stored as separate tables in different locations, but from the user point of view, the partitioned table is still a single table. Syntactically, this implements a number of new extensions to the CREATE TABLE, ALTER TABLE, and EXPLAIN … SELECT statements. As of MySQL 5.1.6, queries against partitioned tables can take advantage of partition pruning. In some cases, this can result in query execution that is an order of magnitude faster than the same query against a non-partitioned version of the same table. See Chapter 18, Partitioning, for further information on this functionality. (Author: Mikael Ronström)
*

Row-based replication. Replication capabilities in MySQL originally were based on propagation of SQL statements from master to slave. This is called statement-based replication. As of MySQL 5.1.5, another basis for replication is available. This is called row-based replication. Instead of sending SQL statements to the slave, the master writes events to its binary log that indicate how individual table rows are effected. As of MySQL 5.1.8, a third option is available: mixed. This will use statement-based replication by default, and only switch to row-based replication in particular cases. See Section 16.1.2, "Replication Formats". (Authors: Lars Thalmann, Guilhem Bichot, Mats Kindahl)
*

Plugin API. MySQL 5.1 adds support for a very flexible plugin API that enables loading and unloading of various components at runtime, without restarting the server. Although the work on this is not finished yet, plugin full-text parsers are a first step in this direction. This allows users to implement their own input filter on the indexed text, enabling full-text search capability on arbitrary data such as PDF files or other document formats. A pre-parser full-text plugin performs the actual parsing and extraction of the text and hands it over to the built-in MySQL full-text search. See Section 22.2, "The MySQL Plugin Interface". (Author: Sergey Vojtovich)
*

Event scheduler. MySQL Events are tasks that run according to a schedule. When you create an event, you are creating a named database object containing one or more SQL statements to be executed at one or more regular intervals, beginning and ending at a specific date and time. Conceptually, this is similar to the idea of the Unix crontab (also known as a "cron job") or the Windows Task Scheduler. See Section 19.4, "Using the Event Scheduler". (Author: Andrey Hristov)
*

Server log tables. Before MySQL 5.1, the server writes general query log and slow query log entries to log files. As of MySQL 5.1, the server's logging capabilities for these logs are more flexible. Log entries can be written to log files (as before) or to the general_log and slow_log tables in the mysql database. If logging is enabled, either or both destinations can be selected. The –log-output option controls the destination or destinations of log output. See Section 5.2.1, "Selecting General Query and Slow Query Log Output Destinations". (Author: Petr Chardin)
*

Upgrade program. The mysql_upgrade program (available as of MySQL 5.1.7) checks all existing tables for incompatibilities with the current version of MySQL Server and repairs them if necessary. This program should be run for each MySQL upgrade. See Section 4.4.8, "mysql_upgrade — Check Tables for MySQL Upgrade". (Authors: Alexey Botchkov, Mikael Widenius)
*

MySQL Cluster. MySQL Cluster is now released as a separate product, based on MySQL 5.1 but with the addition of the NDBCLUSTER storage engine. Clustering support is no longer available in mainline MySQL 5.1 releases. MySQL Cluster releases are identified by a 3-part NDB version number; currently, the MySQL Cluster NDB 6.2 and MySQL Cluster NDB 6.3 release series are available for production use.

Some of the changes in MySQL Cluster since MySQL 5.0 are listed here:
o

MySQL Cluster replication. Replication between MySQL Clusters is now supported. It is now also possible to replicate between a MySQL Cluster and a non-cluster database. See Section 17.10, "MySQL Cluster Replication".
o

MySQL Cluster disk data storage. Formerly, the NDBCLUSTER storage engine was strictly in-memory; now, it is possible to store Cluster data (but not indexes) on disk. This allows MySQL Cluster to scale upward with fewer hardware (RAM) requirements than previously. In addition, the Disk Data implementation includes a new "no-steal" restoration algorithm for fast node restarts when storing very large amounts of data (terabyte range). See Section 17.11, "MySQL Cluster Disk Data Tables", for more information.
o

Improved backups for MySQL Cluster. A fault arising in a single data node during a Cluster backup no longer causes the entire backup to be aborted, as occurred in previous versions of MySQL Cluster.

Many other new features and improvements have been made to the NDBCLUSTER storage engine in MySQL Cluster NDB 6.2 and MySQL Cluster NDB 6.3; for more information about these, see Section 17.14, "MySQL Cluster Development Roadmap".
*

Backup of tablespaces. The mysqldump utility now supports an option for dumping tablespaces. Use -Y or –all-tablespaces to enable this functionality.
*

Improvements to INFORMATION_SCHEMA. MySQL 5.1 provides much more information in its metadata database than was available in MySQL 5.0. New tables in the INFORMATION_SCHEMA database include FILES, EVENTS, PARTITIONS, PROCESSLIST, ENGINES, and PLUGINS.
*

XML functions with XPath support. ExtractValue() returns the content of a fragment of XML matching a given XPath expression. UpdateXML() replaces the element selected from a fragment of XML by an XPath expression supplied by the user with a second XML fragment (also user-supplied), and returns the modified XML. See Section 11.10, "XML Functions". (Author: Alexander Barkov)
*

Load emulator. The mysqlslap program is designed to emulate client load for a MySQL server and report the timing of each stage. It works as if multiple clients were accessing the server. See Section 4.5.7, "mysqlslap — Load Emulation Client". (Authors: Patrick Galbraith, Brian Aker)



--
Thanks,
B.Chandrashekhar.

How to Make best use of Mysql Memory Variables

1. group_concat_max_len

Option Sets Variable

Yes, group_concat_max_len

Variable Name

group_concat_max_len

Variable Scope

Both

Dynamic Variable

Yes

Value Set

Platform Bit Size

32

Type

numeric

Default

1024

Range

4-4294967295

Value Set

Platform Bit Size

64

Type

numeric

Default

1024

Range

4-18446744073709547520

The maximum allowed result length in bytes for the GROUP_CONCAT() function. The default is 1024.

2. join_buffer_size

Option Sets Variable

Yes, join_buffer_size

Variable Name

join_buffer_size

Variable Scope

Both

Dynamic Variable

Yes

Value Set

Platform Bit Size

64

Type

numeric

Default

131072

Range

8200-18446744073709547520

The size of the buffer that is used for plain index scans, range index scans, and joins that do not use indexes and thus perform full table scans. Normally, the best way to get fast joins is to add indexes. Increase the value of join_buffer_size to get a faster full join when adding indexes is not possible. One join buffer is allocated for each full join between two tables. For a complex join between several tables for which indexes are not used, multiple join buffers might be necessary.

The maximum allowable setting for join_buffer_size is 4GB.

3. key_buffer_size

Option Sets Variable

Yes, key_buffer_size

Variable Name

key_buffer_size

Variable Scope

Global

Dynamic Variable

Yes

Value Set

Type

numeric

Default

8388608

Range

8-4294967295

Index blocks for MyISAM tables are buffered and are shared by all threads. key_buffer_size is the size of the buffer used for index blocks. The key buffer is also known as the key cache.

The maximum allowable setting for key_buffer_size is 4GB on 32-bit platforms. As of MySQL 5.0.52, values larger than 4GB are allowed for 64-bit platforms (except 64-bit Windows, for which large values are truncated to 4GB with a warning). The effective maximum size might be less, depending on your available physical RAM and per-process RAM limits imposed by your operating system or hardware platform. The value of this variable indicates the amount of memory requested. Internally, the server allocates as much memory as possible up to this amount, but the actual allocation might be less.

Increase the value to get better index handling (for all reads and multiple writes) to as much as you can afford. Using a value that is 25% of total memory on a machine that mainly runs MySQL is quite common. However, if you make the value too large (for example, more than 50% of your total memory) your system might start to page and become extremely slow. MySQL relies on the operating system to perform file system caching for data reads, so you must leave some room for the file system cache. Consider also the memory requirements of other storage engines.

For even more speed when writing many rows at the same time, use LOCK TABLES. See Section 7.2.19, "Speed of INSERT Statements".

You can check the performance of the key buffer by issuing a SHOW STATUS statement and examining the Key_read_requests, Key_reads, Key_write_requests, and Key_writes status variables. (See Section 12.5.5, "SHOW Syntax".) The Key_reads/Key_read_requests ratio should normally be less than 0.01. The Key_writes/Key_write_requests ratio is usually near 1 if you are using mostly updates and deletes, but might be much smaller if you tend to do updates that affect many rows at the same time or if you are using the DELAY_KEY_WRITE table option.

The fraction of the key buffer in use can be determined using key_buffer_size in conjunction with the Key_blocks_unused status variable and the buffer block size, which is available from the key_cache_block_size system variable:

1 - ((Key_blocks_unused × key_cache_block_size) / key_buffer_size)

This value is an approximation because some space in the key buffer may be allocated internally for administrative structures.

It is possible to create multiple MyISAM key caches. The size limit of 4GB applies to each cache individually, not as a group. See Section 7.4.6, "The MyISAM Key Cache".

4. max_allowed_packet

Option Sets Variable

Yes, max_allowed_packet

Variable Name

max_allowed_packet

Variable Scope

Both

Dynamic Variable

Yes

Value Set

Type

numeric

Default

1048576

Range

1024-1073741824

The maximum size of one packet or any generated/intermediate string.

The packet message buffer is initialized to net_buffer_length bytes, but can grow up to max_allowed_packet bytes when needed. This value by default is small, to catch large (possibly incorrect) packets.

You must increase this value if you are using large BLOB columns or long strings. It should be as big as the largest BLOB you want to use. The protocol limit for max_allowed_packet is 1GB. The value should be a multiple of 1024; non-multiples are rounded down to the nearest multiple.

5. max_connections

Option Sets Variable

Yes, max_connections

Variable Name

max_connections

Variable Scope

Global

Dynamic Variable

Yes

Value Set

Type

numeric

Default

100

The number of simultaneous client connections allowed. By default, this is 100. See Section B.1.2.7, "Too many connections", for more information.

6. max_join_size

Option Sets Variable

Yes, max_join_size

Variable Name

max_join_size

Variable Scope

Both

Dynamic Variable

Yes

Value Set

Type

numeric

Default

4294967295

Range

1-4294967295

Do not allow SELECT statements that probably need to examine more than max_join_size rows (for single-table statements) or row combinations (for multiple-table statements) or that are likely to do more than max_join_size disk seeks. By setting this value, you can catch SELECT statements where keys are not used properly and that would probably take a long time. Set it if your users tend to perform joins that lack a WHERE clause, that take a long time, or that return millions of rows.

Setting this variable to a value other than DEFAULT resets the value of sql_big_selects to 0. If you set the sql_big_selects value again, the max_join_size variable is ignored.

If a query result is in the query cache, no result size check is performed, because the result has previously been computed and it does not burden the server to send it to the client.

This variable previously was named sql_max_join_size.

7. max_length_for_sort_data

Option Sets Variable

Yes, max_length_for_sort_data

Variable Name

max_length_for_sort_data

Variable Scope

Both

Dynamic Variable

Yes

Value Set

Type

numeric

Default

1024

Range

4-8388608

The cutoff on the size of index values that determines which filesort algorithm to use. See Section 7.2.13, "ORDER BY Optimization".

8. max_user_connections

Option Sets Variable

Yes, max_user_connections

Variable Name

max_user_connections

Variable Scope

Both

Dynamic Variable

Yes

Value Set

Type

numeric

Range

1-4294967295

The maximum number of simultaneous connections allowed to any given MySQL account. A value of 0 means "no limit."

Before MySQL 5.0.3, this variable has only global scope. Beginning with MySQL 5.0.3, it also has a read-only session scope. The session variable has the same value as the global variable unless the current account has a non-zero MAX_USER_CONNECTIONS resource limit. In that case, the session value reflects the account limit.

9. query_alloc_block_size

Option Sets Variable

Yes, query_alloc_block_size

Variable Name

query_alloc_block_size

Variable Scope

Both

Dynamic Variable

Yes

Value Set

Platform Bit Size

32

Type

numeric

Default

8192

Range

1024-4294967295

Value Set

Platform Bit Size

64

Type

numeric

Default

8192

Range

1024-18446744073709547520

The allocation size of memory blocks that are allocated for objects created during statement parsing and execution. If you have problems with memory fragmentation, it might help to increase this a bit.

10. query_cache_limit

Option Sets Variable

Yes, query_cache_limit

Variable Name

query_cache_limit

Variable Scope

Global

Dynamic Variable

Yes

Value Set

Platform Bit Size

32

Type

numeric

Default

1048576

Range

0-4294967295

Value Set

Platform Bit Size

64

Type

numeric

Default

1048576

Range

0-18446744073709547520

Don't cache results that are larger than this number of bytes. The default value is 1MB.

11. query_cache_size

Option Sets Variable

Yes, query_cache_size

Variable Name

query_cache_size

Variable Scope

Global

Dynamic Variable

Yes

Value Set

Platform Bit Size

32

Type

numeric

Default

0

Range

0-4294967295

Value Set

Platform Bit Size

64

Type

numeric

Default

0

Range

0-18446744073709547520

The amount of memory allocated for caching query results. The default value is 0, which disables the query cache. The allowable values are multiples of 1024; other values are rounded down to the nearest multiple. Note that query_cache_size bytes of memory are allocated even if query_cache_type is set to 0. See Section 7.5.4.3, "Query Cache Configuration", for more information.

The query cache needs a minimum size of about 40KB to allocate its structures. (The exact size depends on system architecture.) If you set the value of query_cache_size too small, you'll get a warning, as described in Section 7.5.4.3, "Query Cache Configuration".

12. sort_buffer_size

Option Sets Variable

Yes, sort_buffer_size

Variable Name

sort_buffer_size

Variable Scope

Both

Dynamic Variable

Yes

Value Set

Platform Bit Size

32

Type

numeric

Default

2097144

Max Value

4294967295

Value Set

Platform Bit Size

64

Type

numeric

Default

2097144

Max Value

18446744073709547520

Each thread that needs to do a sort allocates a buffer of this size. Increase this value for faster ORDER BY or GROUP BY operations. See Section B.1.4.4, "Where MySQL Stores Temporary Files".

13. table_cache

Option Sets Variable

Yes, table_cache

Variable Name

table_cache

Variable Scope

Global

Dynamic Variable

Yes

Deprecated

5.1.3, by table_open_cache

Value Set

Type

numeric

Default

64

Range

1-524288

The number of open tables for all threads. Increasing this value increases the number of file descriptors that mysqld requires. You can check whether you need to increase the table cache by checking the Opened_tables status variable. See Section 5.1.6, "Server Status Variables". If the value of Opened_tables is large and you don't do FLUSH TABLES often (which just forces all tables to be closed and reopened), then you should increase the value of the table_cache variable. For more information about the table cache, see Section 7.4.8, "How MySQL Opens and Closes Tables".

14. table_lock_wait_timeout

Version Introduced

5.0.10

Option Sets Variable

Yes, table_lock_wait_timeout

Variable Name

table_lock_wait_timeout

Variable Scope

Global

Dynamic Variable

Yes

Value Set

Type

numeric

Default

50

Range

1-1073741824

Specifies a wait timeout for table-level locks, in seconds. The default timeout is 50 seconds. The timeout is active only if the connection has open cursors. This variable can also be set globally at runtime (you need the SUPER privilege to do this). It's available as of MySQL 5.0.10.

15. tmp_table_size

Option Sets Variable

Yes, tmp_table_size

Variable Name

tmp_table_size

Variable Scope

Both

Dynamic Variable

Yes

Value Set

Type

numeric

Default

system dependent

Range

1024-4294967295

The maximum size of internal in-memory temporary tables. (The actual limit is determined as the smaller of max_heap_table_size and tmp_table_size.) If an in-memory temporary table exceeds the limit, MySQL automatically converts it to an on-disk MyISAM table. Increase the value of tmp_table_size (and max_heap_table_size if necessary) if you do many advanced GROUP BY queries and you have lots of memory. This variable does not apply to user-created MEMORY tables.

Additionally, the formula should probably be extended:

total =
innodb_buffer_pool_size +
key_buffer_size +
innodb_additional_mem_pool_size +
innodb_log_buffer_size +
max_connections *
(sort_buffer_size +
read_buffer_size +
binlog_cache_size +
maximum_thread_stack_size);



--
Thanks,
B.Chandrashekhar.