Code

Coding, Programming & Algorithms, Tips, Tweaks & Hacks
Search

Sponsored Ads
WebFaction
Opera
Recent Readers
Sponsored Ads
Inkfruit
MadMimi
  • Mad Mimi Email Marketing

One-liner check for the existence of all required fields from a POSTed form

If you have a simple contact / registration form for a non-CMS / non-framework website with many input fields, it becomes cumbersome to do a server check if all fields passed through doing isset for every field. Many people just check for the existance of a single POST field, but for security reasons, it is better to check for the existence of all required fields.

PHP
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['phone']) && isset($_POST['message']))
{
    # POSTed
    # Process form
}
PHP

What if there were 20 fields ? That'll be one long line of issets.
array_diff is a built-in array function in PHP that computes the difference between arrays - it returns an array containing all the entries from the first array that are not present in any of the other arrays.
All we need to check is if the list of required fields are all present as keys in $_POST - this is easily achievable by checking against array_keys of $_POST.
And finally for the count - if all required fields are present in the $_POST's keys, it'll return 0 which is what we want and how we can confirm that all POST field values got sent through.

PHP
$requiredFields = array('name','email','phone','message');
if (count(array_diff($requiredFields, array_keys($_POST))) == 0)
{
    # POSTed
    # Process form
}
PHP
Vanakkam !

Python2's String = Python3's Text Vs. Data

A significant change from Python 2 to Python 3 is the way strings are dealt with.
Python 3 doesnt always return a string when expected.
For example, the return type of read() in version 2 has always been a string. But in version 3, its very often a "bytes" string.
When you print a "bytes" string, you'll see every character in its byte format, special characters as escape secquences (newline as \n) and other unicode characters as escape sequences.
This is because Python 3 differentiates between text (string) and data ("bytes" string) as oppossed to Unicode vs 8-bit string. (Text Vs. Data Instead Of Unicode Vs. 8-bit)

My localhost/index.html contains just this :
<html><body><h1>It works!. stärke gläser</h1></body></html>

Python 2.x
import urllib

url = "http://localhost"
fp = urllib.urlopen(url)
data = fp.read()
print "%s, %s" % (type(data), type(data).__name__)
print data
Python 2.6.4
Python 2.x
~$ python
Python 2.6.4 (r264:75706, Nov 2 2009, 14:44:17)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib
>>> url = "http://localhost"
>>> fp = urllib.urlopen(url)
>>> data = fp.read()
>>> print "%s, %s" % (type(data), type(data).__name__)
<type 'str'>, str
>>> print data
<html><body><h1>It works!. stärke gläser</h1></body></html>

>>>
Python 2.6.4

In Python 3, we need to need to explicitly convert it to string format via the str() function and specify the encoding-type.
If you are getting errors using Python 3.0, you may want to update to atleast Python 3.0.1 - many have reported possible Unciode encoding/decoding bugs in 3.0.

Python 3.x
import urllib.request

url = "http://localhost"
fp = urllib.request.urlopen(url)
data = fp.read()
print ("%s, %s" % (type(data), type(data).__name__))
print (data)
data = str(data,'utf-8') # convert a byte datatype to string datatype using utf-8 encoding. For ASCII, data = str(data,'ascii')
print (data)
Python 3.1.1
Python 3.x
~$ python3
Python 3.1.1+ (r311:74480, Oct 12 2009, 02:14:03)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib.request
>>> url = "http://localhost"
>>> fp = urllib.request.urlopen(url)
>>> data = fp.read()
>>> print ("%s, %s" % (type(data), type(data).__name__))
<class 'bytes'>, bytes
>>> print (data)
b'<html><body><h1>It works!. st\xc3\xa4rke gl\xc3\xa4ser</h1></body></html>\n'
>>> data = str(data,'utf-8') # convert a byte datatype to string datatype using utf-8 encoding. For ASCII, data = str(data,'ascii')
>>> print (data)
<html><body><h1>It works!. stärke gläser</h1></body></html>

>>>
Python 3.1.1
Vanakkam !

Sorting a String in SQL

Even though stored procedures are really slow, sometimes they come in handy.
SQL
DROP FUNCTION IF EXISTS `SORTEDSTRING`;
DELIMITER ///
CREATE FUNCTION SORTEDSTRING(s VARCHAR(1000)) RETURNS VARCHAR(1000) DETERMINISTIC
BEGIN
    DECLARE i INT DEFAULT 1;
    DECLARE j INT;
    DECLARE si CHAR(1);
    DECLARE sj CHAR(1);
    DECLARE ss VARCHAR(1000); -- Sorted String

    SET ss = s;
    SET @length = LENGTH(s);

    WHILE i < @length DO
        SET j = i + 1;
        WHILE j <= @length DO
            SET si = SUBSTRING(ss, i, 1);
            SET sj = SUBSTRING(ss, j, 1);
            IF si > sj THEN
                SET ss = INSERT(ss, i, 1, sj);
                SET ss = INSERT(ss, j, 1, si);
            END IF;
            SET j = j + 1;
        END WHILE;
        SET i = i + 1;
    END WHILE;

    RETURN ss;
END
///
DELIMITER ;

mysql> SELECT SORTEDSTRING("elephant");
+--------------------------+
| SORTEDSTRING("elephant") |
+--------------------------+
| aeehlnpt                 |
+--------------------------+
1 row in set (0.00 sec)

mysql>
MySQL 5.0
Vanakkam !

Loading AJAX locally, without a webserver

So far, while developing web applications I have always taken one point into assumption - that it has to run on a web-server. But when dealing with pure client-side web apps, we often overlook the fact that it should be able to be run by simply double-clicking on the homepage file (index.html). When XMLHttpRequest's readyState reaches a value of 4, we further check for a response code 200 from the web-server before doing anything with the responseText / responseXML. But when running it locally - not on a webserver, the status code value will alway be 0.
JavaScript
window.onload = function()
{
    var xhr = NewXMLHttpRequest();
    if (xhr != false)
    {
        try
        {
            xhr.open("GET", "local-ajax.txt", true);
            xhr.onreadystatechange = xhr_load;
            xhr.setRequestHeader("Connection", "close");
            xhr.send(null);
        }
        catch(e)
        {
            alert("Error Loading File\n" + e.code + "\n" + e.message);
        }
    }
    else
    {
        alert("AJAX not supported");
    }
}

function xhr_load()
{
    switch (this.readyState)
    {
        case 1: // Open
        case 2: // Send
        case 3: // Receiving
        break;

        case 4: // Loaded
        if (this.status == 200 || (this.status == 0 && document.location.protocol == "file:")) // OK
        {
            var text = this.responseText;
            alert(text);
        }
        break;
    }
}

function NewXMLHttpRequest()
{
    var xhr = false;

    if (window.XMLHttpRequest) // native XMLHttpRequest object
    {
        try { xhr = new XMLHttpRequest(); }
        catch(e) { xhr = false; }
    }
    else if (window.ActiveXObject) // IE/Windows ActiveX version
    {
        try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); }
        catch(e)
        {
            try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
            catch(e) { xhr = false; }
        }
    }

    return xhr;
}
JavaScript 1.5
Vanakkam !

1 pixel wide line parallel to the axis in HTML's Canvas element

I was playing around with HTML's Canvas element and I spent a whole day trying to figure out why I can't draw a 1-pixel wide straight line (parallel to the axes). If you try dawing a black (#000000) straight line parallel to the axes, then for all odd numbered widths :
  • the first line is of colour #9d9d9d and the last one is of #8d8d8d
  • The width of the line is one pixel more
Canvas Lines
<html>
<head>
        <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
        <title>HTML5 - Canvas</title>
        <meta http-equiv="Content-Language" content="en-us"/>
        <script type="text/javascript">
        function foo()
        {
            var canvas = document.getElementById("canvas-line");
            var ctx = canvas.getContext('2d');
            
            for (i = 1, j = 0; i < 15; i++, j+=i+7)
            {
                ctx.beginPath();
                ctx.lineWidth = i;
                ctx.strokeStyle = "black";
                ctx.moveTo(50,25 + j);
                ctx.lineTo(300,25 + j);
                ctx.stroke();
            }
        }

        </script>
</head>
<body onload="foo()">
<canvas id="canvas-line" width="350" height="250" style="border:1px solid #cf1313; margin-left:100px;"></canvas>
</body>
</html>
HTML 5 + JavaScript
The above should give an output like this : If you zooom in, you should be able to see the top and bottom border colours. This happens in all canvas-supported browsers (FF 3, FF 3.5 beta 4, Opera 10 beta, Chrome 2 beta, Safari 4 beta). Reason : https://developer.mozilla.org/en/Canvas_tutorial/Applying_styles_and_colors#section_8 Mozilla's canvas tutorial on drawing shapes shows a screenshot which has the inner most rectangle of exactly 1 pixel wide and colour black. But viewing the example itself in the browser, shows otherwise - 2 pixel wide with faded colours. I've written a small function that draws exactly 1 pixel wide straight line parallel to the axis.
1 pixel wide Canvas line
<html>
<head>
        <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
        <title>HTML5 - Canvas</title>
        <meta http-equiv="Content-Language" content="en-us"/>
        <script type="text/javascript">
        /*
        draw1pxLinePA
            Draw a 1 pixel width line parallel to the axis
        Parameters
            x : x coordinate
            y : y coordinate
            l : length
            o : orientation
                0 = horizontal (default)
                1 = vertical
            bg : erase-with colour - for background
        */
        CanvasRenderingContext2D.prototype.draw1pxLinePA = function(x, y, l, o, bg)
        {
            o = o || 0;
            bg = bg || "white";

            this.beginPath();
            this.lineWidth = 2; // 1 creates a 2 pixel wide line with fading
            this.moveTo(x, y);
            this.lineTo(x + (l * !o), y + (l * o));
            this.stroke();

            var strokeStyle = this.strokeStyle; // Save current strokeStyle

            // Erase the extra line
            this.beginPath();
            this.lineWidth = 2;
            this.strokeStyle = bg;
            this.moveTo(x + (1 * o), y + (1 * !o));
            this.lineTo(x + (l * !o) + (1 * o), y + (l * o) + (1 * !o));
            this.stroke();

            this.strokeStyle = strokeStyle; // Restore strokeStyle
        }

        function foo()
        {
            var canvas = document.getElementById("canvas-line");
            var ctx = canvas.getContext('2d');

            ctx.strokeStyle = "black";
            ctx.draw1pxLinePA(20, 20, 260, 1);
            ctx.draw1pxLinePA(30, 150, 400);
        }

        </script>
</head>
<body onload="foo()">

<canvas id="canvas-line" width="450" height="300" style="border:1px solid #cf1313; margin-left:100px;"></canvas>

</body>
</html>
HTML 5 + JavaScript
Vanakkam !

Property getters & setters

In traditional OOP, if we wanted to get or set an object's private member, we would need to write a public method to do the job.
The reason behind making a member data private and then accessing it through a public method is to avoid the implementing-user to access it directly.
There can be many reasons for prohibiting direct access to member data to the implementing-code.
For example, you may want a radius of a Circle to be within the range of 10 - 500.

C++: Traditional OOP
class Circle
 {
        private:
          int radius;

        public:
          Circle(int radius = 15)
           {
                  setRadius(radius);
           }

          void setRadius(int radius)
           {
                  if (radius < 10 || radius > 500)
                   {
                          this->radius = -1;
                          cout << "Radius must be within the range of 10 - 500" << endl;
                   }
                  else
                   this->radius = radius;
           }

          int getRadius()
           {
                  return this->radius;
           }
 }

void main()
 {
        Circle c = Circle();
        c.setRadius(25);
        cout << c.getRadius();
 }
C++

In languages like PHP & Python & PERL which have a weak type system, a further check of the data type may be necessary.
But for Python unfortunately even traditional getter & setter methods cannot be implemted because Python doesn't have a public or private. Everything is public by default - though a member can be made private by prefixing two underscores to it. But this is only for convention, it doesn't really serve its true purpose.

PHP 5 and C# .NET have a getter and setter method feature, making it look like we're accessing the data member directly.

PHP
<?php
class Circle
 {
        private $radius; # integer

        # Constructor
        public function __construct($radius = 15)
         {
                self::__set('radius', $radius);
         }

        # Setter
        public function __set($name, $value)
         {
                switch ($name)
                 {
                        case 'radius':

                          if (!is_numeric($value)) # is_int() for strong type checking
                           throw new Exception('Radius must be of a numeric type');

                          if ($value < 10 || $value > 500)
                           throw new Exception('Radius must be within the range of 10 - 500');

                          $this->radius = $value;

                        break;

                        default:
                          throw new Exception("Attempt to set a non-existing property: $name");
                        break;
                 }
         }

        # Getter
        public function __get($name)
         {
                if (in_array($name, array('radius')))
                 return $this->$name;

                switch ($name)
                 {
                        default:
                          throw new Exception("Attempt to get a non-existing property: $name");
                        break;
                 }
         }

 }

$c = new Circle();
$c->radius = 25;
echo $c->radius;
>
PHP 5.x
C#
using System;

public class Circle
 {
        private int __radius = 5;

        public Circle()
         {
         }

        public Circle(int radius)
         {
                this.radius = radius; // This will call the property defined below
         }

        public int radius // Property getter/setter name cannot be the same as the member variable name
         {
                get
                 {
                        return __radius;
                 }

                set
                 {
                        if (value < 10 || value > 500)
                         throw new Exception("Radius must be within the range of 10 - 500");

                        __radius = value;
                 }
         }
 }

public class main
 {
        public static void Main(string[] args)
         {
                Circle c = new Circle(); // Circle c = new Circle(5); will throw an Exception
                c.radius = 25;
                Console.WriteLine(c.radius);
         }
 }
.NET 2.0

C# .NET 3.0 has introduced Automatic Properties where you don't need to specify code for the getter & setter - the compiler takes generates the method body.

JavaScript does seem to have a getter and setter method which I came across just now when searching for the official source to Java 7's new features' documentation, but :

  • only within an object initializer - not inside a function so it doesn't seem to be of much use as we can't create instances
  • doesn't hide the member from being accessed directly
  • doesn't work in IE.

JavaScript
var someObj =
 {
        a : 7,
        get b()
         {
                return this.a * 3;
         },
        set c(x)
         {
                this.a = x / 2;
         }
 }

someObj.foo1 = function()
 {
        //
 }

alert(someObj.a); // 7
alert(someObj.b); // 21
someObj.c = 5; alert(someObj.a); // 2.5
someObj.foo1();
JavaScript 1.5

The Getter & Setter feature does not seem to be a much "wanted" feature in the Java community.
Still, this has been proposed by Rémi Forax for JDK 7.

Java: Proposal
public class Circle
 {
        private int __radius = 5;

        public Circle()
         {
         }

        public Circle(int radius)
         {
                this.radius = radius; // This will call the property defined below
         }

        public property int radius // Property getter/setter name cannot be the same as the member variable name
         {
                get
                 {
                        return __radius;
                 }

                set (int radius)
                 {
                        if (radius < 10 || radius > 500)
                         throw new Exception("Radius must be within the range of 10 - 500");

                        __radius = radius;
                        // firePropertyChange(radius);
                 }
         }

        public static void main(String[] args)
         {
                Circle c = new Circle(2); // Circle c = new Circle(5); will throw an Exception
                c.radius = 25;
                System.out.println(c.radius);
         }
 }
JDK 7
Vanakkam !

Python's Classmethods

Lets say I have an abstract class called Vehicle and 3 classes that descend from it are Bike, Car & Truck.
I use a static variable in Vehicle called total to keep track of the total number of Vehicles. But I really don't want to keep track of the total number general Vehicles. What I really want is to keep track of the total number of Bikes, Cars & Trucks individually. This is easy - just declare total in Bike, Car & Truck classes.

Now arises a situation where we need a function println in Vehicle that accesses total. We'll also include a function called set in Vehicle to explicitly set the value of total (instead of creating 10 instances to prove a point).

There are two scenarios to this, both of which are not possible :

  1. Declare a static variable total in Vehicle but different values persist in Bike::total, Car::total & Truck::total. This is impossible because total is Vehicle's static variable which is common to all. The following will output 2 2 2.
    PHP
    <?php
    abstract class Vehicle
     {
            protected static $total;
    
            public static function println()
             {
                    echo self::$total."\n";
             }
    
            public static function set($value)
             {
                    self::$total = $value;
             }
     }
    
    class Bike extends Vehicle
     {
     }
    
    class Car extends Vehicle
     {
     }
    
    class Truck extends Vehicle
     {
     }
    
    Bike::set(3);
    Car::set(5);
    Truck::set(2);
    
    $b = new Bike();
    $c = new Car();
    $t = new Truck();
    
    Bike::println()
    Car::println()
    Truck::println()
    
    // Is there any way for Bike's static variable to hold 3 and Car's static to hold 5 & Truck's static to hold 2 ?
    ?>
    PHP 5.2.5
  2. Declare the static variable total in each of Vehicle's subclasses, Bike, Car & Truck. But in this case, Vehicle's println needs to access the descendant class static variable like child::total which is not possible in most(all) languages.
    PHP
    <?php
    abstract class Vehicle
     {
            public static function println()
             {
                    echo child::$total."\n";
             }
    
            public static function set($value)
             {
                    child::$total = $value;
             }
     }
    
    class Bike extends Vehicle
     {
            public static $total; # Should've been protected, but then parent wouldn't able to access
     }
    
    class Car extends Vehicle
     {
            public static $total;
     }
    
    class Truck extends Vehicle
     {
            public static $total;
     }
    
    Bike::set(3);
    Car::set(5);
    Truck::set(2);
    
    $b = new Bike();
    $c = new Car();
    $t = new Truck();
    
    Bike::println();
    Car::println();
    Truck::println();
    ?>
    PHP 5.2.5

    It is possible to overcome this problem by setting and getting the value in the subclasses and use $this->childMethod() in the parent class, Vehicle.
    PHP
    <?php
    abstract class Vehicle
     {
            public function set($value)
             {
                    $this->setChildValue($value);
             }
    
            public function println()
             {
                    echo $this->getChildValue()."\n";
             }
     }
    
    class Bike extends Vehicle
     {
            protected static $total;
    
            public function getChildValue()
             {
                    return self::$total;
             }
    
            public function setChildValue($value)
             {
                    self::$total = $value;
             }
     }
    
    class Car extends Vehicle
     {
            protected static $total;
    
            public function getChildValue()
             {
                    return self::$total;
             }
    
            public function setChildValue($value)
             {
                    self::$total = $value;
             }
     }
    
    class Truck extends Vehicle
     {
            protected static $total;
    
            public function getChildValue()
             {
                    return self::$total;
             }
    
            public function setChildValue($value)
             {
                    self::$total = $value;
             }
     }
    
    $b = new Bike();  $b->set(3);
    $c = new Car();   $c->set(5);
    $t = new Truck(); $t->set(2);
    
    $b->println();
    $c->println();
    $t->println();
    ?>
    PHP 5.2.5

    But the two methods, getChildValue and setChildValue must be defined properly in all subclasses.
    __CLASS__ returns the class in which its called from and get_class($this) returns the class of the current instance.
    Example : echo __CLASS__; in a method in Vehicle will always output Vehicle, but get_class($this) will output the classname of the object (In this case, Bike, Car or Truck).
    If we could do get_class($this)::$total (Bike::$total), then it could've been easily solved.

    PHP
    <?php
    abstract class Vehicle
     {
            public function set($value)
             {
                    get_class($this)::$total = $value;
             }
    
            public function println()
             {
                    echo get_class($this)::$total."\n";
             }
     }
    
    class Bike extends Vehicle
     {
            public static $total;
     }
    
    class Car extends Vehicle
     {
            public static $total;
     }
    
    class Truck extends Vehicle
     {
            public static $total;
     }
    
    $b = new Bike();  $b->set(3);
    $c = new Car();   $c->set(5);
    $t = new Truck(); $t->set(2);
    
    $b->println();
    $c->println();
    $t->println();
    ?>
    PHP 5.2.5

The last method is possible in Python in two ways - self.__class__.total & classmethod. Python has a way to access class member of the caller's class, not just the class members in which its being accessed. Here each of the subclasses have a static member called total which gets created and assigned in its parent, Vehicle

Python : Using __class__
class Vehicle:

      def println(self):
          print self.__class__.total

      def set(self, value):
          self.__class__.total = value

class Bike(Vehicle):
          pass

class Car(Vehicle):
          pass

class Truck(Vehicle):
          pass

Bike().set(3)   # Bike.total = 3
Car().set(5)    # Car.total = 5
Truck().set(2)  # Truck.total = 2

b = Bike()
c = Car()
t = Truck()

b.println()
c.println()
t.println()
Python 2.5.1
Python : Using classmethod
class Vehicle:

      @classmethod
      def println(cls):
          print cls.total

      @classmethod
      def set(cls, value):
          cls.total = value

class Bike(Vehicle):
          pass

class Car(Vehicle):
          pass

class Truck(Vehicle):
          pass

Bike.set(3)   # Bike.total = 3
Car.set(5)    # Car.total = 5
Truck.set(2)  # Truck.total = 2

b = Bike()
c = Car()
t = Truck()

b.println()
c.println()
t.println()

Bike.println()
Car.println()
Truck.println()
Python 2.5.1

self.__class__.total points to the static member total of the object's (this) class and not of the class Vehicle.
cls.total references the same thing as the first argument is actually the classname which is not passed in the parentheses, but by using the classname preceding the dot.

Vanakkam !

Export MySQL data to Excel compatible CSV format

One of the most often used feature in front-end GUI tools like phpMyAdmin is to export your data to an Microsoft Excel compatible CSV format. Excel compatible because, CSV functions in Python, PHP, Java or C# can read CSV files created using Excel. Because there is no CSV standard, we'll use Microsoft Excel's CSV format. Microsoft Excel uses 2 double-quotes to indicate a double-quote within a column-value enclosed by double-quotes.
For example, a Hello"World in Excel is internally "Hello""World" if you open the file in Notepad.

When you're dealing with large sets of data, its better to use MySQL in command-line mode for export. A stand-alone Py/PHP/Java script may do the job but it would still be faster in MySQL command-line mode.

Lets take a simple person-info table type as an example. `persons` is a table in database `community`.

MySQL
CREATE TABLE IF NOT EXISTS `persons` (
  `ID` bigint(20) NOT NULL auto_increment,
  `Name` varchar(255) NOT NULL,
  `Address` varchar(255) NOT NULL,
  `City` varchar(255) NOT NULL,
  `State` varchar(255) NOT NULL,
  `Zip` varchar(255) NOT NULL,
  `Phone` varchar(255) NOT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
MySQL 5.0.45
  1. mysqldump

    Dumping SQL via the mysqldump command-line tool is the most common use for database backup. Using mysqldump, it is possible to export to CSV but there are some limitations :

    • Its not possible to select columns, so you end up exporting all columns. And I can't see options for columns in the newer versions, 5.1 or 6.0, so I guess theres no way out here.
    • When exporting to CSV format, we indicate the column data is to be seperated by a comma by specifying options such as --fields-terminated-by=",". When using --fields-xx options, its mandatory to use the --tab=<dir name> option which specifies the folder to dump to. --tab accepts a foldername because it'll export the tables in a separate file text format to that folder. Even if we select only one table to dump, it'll still have to dump to the specified folder. So we can't output to a file by using pipe (mysqldump ... > los-angeles-persons.csv).
      Note: --result-file=<filename> option is used to output to a specified file but not in conjunction with the --tab option.
    • Its not possible to sort the result, expect by the PK (Primary Key) column by specifying the --order-by-primary option.
    mysqldump community persons --user=root --where="`City` LIKE '%Los Angeles%'" --tab="csv data" --fields-terminated-by="," --fields-enclosed-by="\"" --fields-escaped-by="\"\"" --lines-terminated-by="\r\n" --no-create-db --no-create-info -p

    This will export (dump) all persons located in Los Angeles into a folder named csv data (an existing folder relative to your current path).
    --fields-escaped-by="\"\"" : specify 2 double-quotes("") to indicate a double-quote(") - since the column values are enclosed by double-quotes(").
    Internally, this executes a SELECT INTO OUTFILE query.

  2. SELECT ... INTO OUTFILE

    Enter mysql in command-line mode.

    C:\MySQL\bin>mysql --user=root -p
    Enter password:
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 81
    Server version: 5.0.45-community-nt-log MySQL Community Edition (GPL)
    
    Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
    
    mysql> USE community;
    Database changed
    mysql> SELECT `Name`, `Address`, `City`, `State`, `Zip`, `Phone`
        -> FROM `persons`
        -> WHERE `City` LIKE '%Los Angeles%'
        -> ORDER BY `Name` ASC, `Zip` ASC
        -> INTO OUTFILE 'los-angeles-persons.csv' FIELDS ESCAPED BY '""' TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n';
    Query OK, 299 rows affected (0.05 sec)
    
    mysql>

    This is probably the best option because you're inside the MySQL console.
    This selects only `Name`, `Address`, `City`, `State`, `Zip`, `Phone` columns and again filtered by Los Angeles city.
    The in INTO OUTFILE is relative to the database directory in the MySQL data directory. MySQL data directory is the one assigned to datadir= in the configuration file (my.ini or my.cnf).
    My path is D:\Data\MySQL\community\los-angeles-persons.csv (for default setup : C:\MySQL\data\community\los-angeles-persons.csv)

    Unfortunately, export options (FIELDS ESCAPED BY '""' TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n') can only be used with INTO OUTFILE option, so something like this in command-prompt is not possible:

    C:\MySQL\bin>mysql --user=root --database=community --execute="SELECT `Name`, `Address`, `City`, `State`, `Zip`, `Phone` FROM `persons` WHERE `City` LIKE '%Los Angeles%' ORDER BY `Name` ASC, `Zip` ASC FIELDS ESCAPED BY '\"\"' TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\r\n';" -p > los-angeles-persons.csv
  3. CONCAT()

    Because of limitations of the first two methods, piping output to a file using > is not possible.
    The only other way is to join all the column-values using the CONCAT() function.
    In script.sql enter

    USE `community`;
    
    DROP FUNCTION IF EXISTS toXLCell;
    delimiter ///
    CREATE FUNCTION toXLCell(s VARCHAR(1000)) RETURNS VARCHAR(1000) DETERMINISTIC
    BEGIN
        SET @XLs = CONCAT('"', REPLACE(s,'"','""'), '",');
        RETURN @XLs;
    END;
    ///
    delimiter ;
    
    SELECT
    CONCAT(toXLCell(`Name`), toXLCell(`Address`), toXLCell(`City`), toXLCell(`State`), toXLCell(`Zip`), toXLCell(`Phone`)) AS `Row`
    FROM `persons`
    WHERE `City` LIKE '%Los Angeles%'
    ORDER BY `Name` ASC, `Zip` ASC;
    C:\MySQL\bin>mysql --user=root -p < script.sql > los-angeles-persons.csv

    Using CONCAT & REPLACE may be tedious, but helps in batch scripts.

    This will create an extra empty column at the end because of the trailing comma. If default parameter value was supported , the function could've been defined as toXLCell(s VARCHAR(1000), bLast BIT(1) = FALSE) and toXLCell(`Phone`) would be changed to toXLCell(`Phone`, TRUE)

    MySQL doesn't support variable number of parameters, otherwise we could've had a function
    toXLLine(`Name`, `Address`, `City`, `State`, `Zip`, `Phone`)
    accepting variable number of column names.

Vanakkam !

Form submission using AJAX & HTML

One of the biggest concerns using AJAX based form submissions are JavaScript related issues :
  • What if JavaScript is disabled or not available on the client's browser ?
  • What if XMLHttpRequest / Msxml2.XMLHTTP / Microsoft.XMLHTTP aren't available ?
  • What if the creation of XMLHttpRequest object failed for some reason ?
  • What if all the JavaScript scripts didn't load properly and screwed up the damn thing ?
  • What if the user clicked the button much faster than the scripts to completely load ? You must be on a real slow connection for this to happen.
The only solution is to give your users the option to automatically fall back to the normal form submission if AJAX doesn't work. Relying solely on client side scripting should only be done only if the application demands it.
HTML
<form id="Comment-Form" action="http://mydomain.com/PostComment" method="post">
<div id="Comment-Box">
<table>
<tr><th>Leave a Comment</th></tr>
<tr><td id="Comment-Box-Msg" style="display:none"></td></tr>
<tr><td><textarea name="Comment" id="Comment-Reply" rows="10" cols="50"></textarea></td></tr>
<tr><td style="text-align:center">
<input type="submit" value="Post Comment" name="Submit" id="Comment-Button"/>
</td></tr>
</table>
</div>
</form>
HTML 4.01
JavaScript
window.onload = function() { init(); }
function init()
 {
        /* 
        This is set only after the entire page is loaded,
        so if the button is clicked way before its loaded,
        it'll 'normal' submit to the form's action value
        */
        document.getElementById("Comment-Button").onclick = PostCommment;
 }
function PostCommment()
 {
        // AJAX error : switch to <form> submit
        if (ajax_error) document.getElementById("Comment-Form").submit();

        // Do the form submission via AJAX

        // To stop the <form> being submitted, since its done via AJAX
        return false;
 }
Javascript 1.5
This way, it ensures that if there is a problem with JavaScript or AJAX in particular, you can always fall back to the normal form submission.
Vanakkam !

Generating a Random String

PHP
<?php
class RandomText
 {
        const RAND_NUMBERS       = 1;
        const RAND_SMALL_LETTERS = 2;
        const RAND_CAP_LETTERS   = 4;
        const RAND_ALL           = 7;

        /**
         * @access public
         * @param Type (INT) One of the random constants RAND_*
         * @NoOfChars [INT] Optional - No of characters to generate
         * @return (string) random string
         * @example echo RandomText::Random_String(RandomText::RAND_NUMBERS + RandomText::RAND_CAP_LETTERS, 25);
         */
 	public static function Random_String($Type = self::RAND_NUMBERS, $NoOfChars = 6)
 	 {
 	 	$strList = array();

 	 	// Convert to binary format and find out what combination of random characters are required
 	 	$binType = base_convert($Type, 10, 2);

 	 	// Loop through the bits from Right To Left
 	 	for ($i = strlen($binType) - 1; $i >= 0; $i--)
 	 	 {
 	 	 	if ($binType[$i])
 	 	 	 {
 	 	 	 	switch (pow(2, strlen($binType) - $i - 1))
 	 	 	 	 {
 	 	 	 	 	default:

 	 	 	 	 	case self::RAND_NUMBERS:
 	 	 	 	 	 $Ascii_Range = array(48, 57);  // Numbers - Characters 0 to 9
 	 	 	 	 	break;

 	 	 	 	 	case self::RAND_SMALL_LETTERS:
   	 	 	 	 	 $Ascii_Range = array(97, 122); // Small Letters - Characters a to z
 	 	 	 	 	break;

 	 	 	 	 	case self::RAND_CAP_LETTERS:
 	 	 	 	 	 $Ascii_Range = array(65, 90);  // Capital Letters - Characters A to Z
 	 	 	 	 	break;
 	 	 	 	 }

 	 	 	 	for ($j = $Ascii_Range[0]; $j <= $Ascii_Range[1]; $j++)
 	 	 	 	 $strList[] = chr($j);
 	 	 	 }
 	 	 }

 	 	$RndString = "";
 	 	for ($i = 0; $i < $NoOfChars; $i++)
 	 	 $RndString .= $strList[rand(0, count($strList) - 1)];

 	 	return $RndString;
 	 }
 }

echo RandomText::Random_String(RandomText::RAND_NUMBERS + RandomText::RAND_CAP_LETTERS, 25);
?>
PHP 5.2.3
C#
using System;
using System.Text;

public class RandomText
 {
        public const int RAND_NUMBERS       = 1;
        public const int RAND_SMALL_LETTERS = 2;
        public const int RAND_CAP_LETTERS   = 4;
        public const int RAND_ALL           = 7;

        public static string Random_String()
         {
                return Random_String(RAND_NUMBERS, 6);
         }

        public static string Random_String(int Type)
         {
                return Random_String(Type, 6);
         }

        public static string Random_String(int Type, int NoOfChars)
         {
                StringBuilder strList = new StringBuilder();
                int[] Ascii_Range;
                int i;

                // Convert to binary format and find out what combination of random characters are required
                string binType = Convert.ToString(Type, 2);

                // Loop through the bits from Right To Left
                for (i = binType.Length - 1; i >= 0; i--)
                 {
                        if (binType[i] == '1')
                         {
                                switch ((int)Math.Pow(2, binType.Length - i - 1))
                                 {
                                        default:

                                        case RAND_NUMBERS:
                                         Ascii_Range = new int[] {48, 57};  // Numbers - Characters 0 to 9
                                        break;

                                        case RAND_SMALL_LETTERS:
                                         Ascii_Range = new int[] {97, 122};  // Small Letters - Characters a to z
                                        break;

                                        case RAND_CAP_LETTERS:
                                         Ascii_Range = new int[] {65, 90};  // Capital Letters - Characters A to Z
                                        break;
                                 }

                                for (int j = Ascii_Range[0]; j <= Ascii_Range[1]; j++)
                                 strList.Append((char)j);
                         }
                 }

 	 	StringBuilder RndString = new StringBuilder();
 	 	Random rnd = new Random();
 	 	
 	 	for (i = 0; i < NoOfChars; i++)
 	 	 RndString.Append(strList[rnd.Next(strList.Length - 1)]);

 	 	return RndString;
         }

        public static void Main(string[] args)
         {
                Console.WriteLine(RandomText.Random_String(RandomText.RAND_NUMBERS + RandomText.RAND_CAP_LETTERS, 25));
         }
 }
.NET 2.0
Java
import java.io.*;
import java.util.Random;

public class RandomText
 {
        public static final int RAND_NUMBERS       = 1;
        public static final int RAND_SMALL_LETTERS = 2;
        public static final int RAND_CAP_LETTERS   = 4;
        public static final int RAND_ALL           = 7;

        public static String Random_String()
         {
                return Random_String(RAND_NUMBERS, 6);
         }

        public static String Random_String(int Type)
         {
                return Random_String(Type, 6);
         }

        public static String Random_String(int Type, int NoOfChars)
         {
                StringBuilder strList = new StringBuilder();
                int[] Ascii_Range;
                int i;

                // Convert to binary format and find out what combination of random characters are required
                String binType = Integer.toString(Type, 2); // Type.toString(2);

                // Loop through the bits from Right To Left
                for (i = binType.length() - 1; i >= 0; i--)
                 {
                        if (binType.charAt(i) == '1')
                         {
                                switch ((int)Math.pow(2, binType.length() - i - 1))
                                 {
                                        default:

                                        case RAND_NUMBERS:
                                         Ascii_Range = new int[] {48, 57};  // Numbers - Characters 0 to 9
                                        break;

                                        case RAND_SMALL_LETTERS:
                                         Ascii_Range = new int[] {97, 122};  // Small Letters - Characters a to z
                                        break;

                                        case RAND_CAP_LETTERS:
                                         Ascii_Range = new int[] {65, 90};  // Capital Letters - Characters A to Z
                                        break;
                                 }

                                for (int j = Ascii_Range[0]; j <= Ascii_Range[1]; j++)
                                 strList.append((char)j);
                         }
                 }

                StringBuilder RndString = new StringBuilder();
                Random rnd = new Random();

                for (i = 0; i < NoOfChars; i++)
                 RndString.append(strList.charAt(rnd.nextInt(strList.length() - 1)));

                return RndString.toString();
         }

        public static void main(String[] args) throws Exception
         {
                System.out.println(RandomText.Random_String(RandomText.RAND_NUMBERS + RandomText.RAND_CAP_LETTERS, 25));
         }
 }
JDK 6.0
JavaScript
function RandomText()
 {
        this.RAND_NUMBERS       = 1;
        this.RAND_SMALL_LETTERS = 2;
        this.RAND_CAP_LETTERS   = 4;
        this.RAND_ALL           = 7;

        this.Random_String = function(Type, NoOfChars)
         {
                var strList = "";
                var Ascii_Range;
                var i;

                // Convert to binary format and find out what combination of random characters are required
                binType = Type.toString(2);

                // Loop through the bits from Right To Left
                for (i = binType.length - 1; i >= 0; i--)
                 {
                        if (binType[i] == '1')
                         {
                                switch (Math.pow(2, binType.length - i - 1))
                                 {
                                        default:

                                        case this.RAND_NUMBERS:
                                         Ascii_Range = new Array(48, 57);  // Numbers - Characters 0 to 9
                                        break;

                                        case this.RAND_SMALL_LETTERS:
                                         Ascii_Range = new Array(97, 122); // Small Letters - Characters a to z
                                        break;

                                        case this.RAND_CAP_LETTERS:
                                         Ascii_Range = new Array(65, 90);  // Capital Letters - Characters A to Z
                                        break;
                                 }

                                for (var j = Ascii_Range[0]; j <= Ascii_Range[1]; j++)
                                 strList += String.fromCharCode(j);
                         }
                 }

                var RndString = "";
                for (i = 0; i < NoOfChars; i++)
                 RndString += strList[Math.floor(Math.random() * strList.length)];

                return RndString;
         }
 }

var oRandomText = new RandomText();
alert(oRandomText.Random_String(oRandomText.RAND_NUMBERS + oRandomText.RAND_CAP_LETTERS, 25));
JavaScript 1.5
Python
import array
import random

def int2bin(n):
    "Convert an integer to binary - no built-in function"
    bStr = ''
    while n > 0:
          bStr = str(n % 2) + bStr
          n = n >> 1
    return bStr

class RandomText:

      RAND_NUMBERS       = 1;
      RAND_SMALL_LETTERS = 2;
      RAND_CAP_LETTERS   = 4;
      RAND_ALL           = 7;

      def Random_String(Type = RAND_NUMBERS, NoOfChars = 6):
          strList = array.array('c', '')

          # Convert to binary format and find out what combination of random characters are required
          binType = int2bin(Type)

          # Loop through the bits from Right To Left
          for i in range(len(binType) - 1, -1, -1):

              if binType[i] == '1':

                 x = 2 ** (len(binType) - i - 1)

                 if x == RandomText.RAND_NUMBERS:
                    Ascii_Range = [48, 57]   # Numbers - Characters 0 to 9
                 elif x == RandomText.RAND_SMALL_LETTERS:
                    Ascii_Range = [97, 122]  # Small Letters - Characters a to z
                 elif x == RandomText.RAND_CAP_LETTERS:
                    Ascii_Range = [65, 90]   # Capital Letters - Characters A to Z
                 else:
                    Ascii_Range = [48, 57]   # Numbers - Characters 0 to 9

                 for j in range(Ascii_Range[0], Ascii_Range[1] + 1):
                    strList.append(chr(j))

              RndString = array.array('c', '')

              for i in range(0, NoOfChars):
                  RndString.append(strList[random.randint(0, len(strList) - 1)])

          return RndString.tostring()

      Random_String = staticmethod(Random_String)


print RandomText.Random_String(RandomText.RAND_NUMBERS + RandomText.RAND_CAP_LETTERS, 25)
Python 2.5
Vanakkam !