Friday, May 28, 2010

What is Singleton Class

A singleton class allows only one instance of an object to be used across the web application.
Where it can be used:
  •  During Database Connection where we want to share only one database connection throughout the web application. So in this case make your database related operation through Singleton Design Pattern.
  • To avoid error like too many connection open.





class YourSingleTonClass
{
 private static $instance;
 
 private function __construct()
 {
 } 
 public function getInstance() {
  if($instance === null) {
   $instance = new YourSingleTonClass();
  }
  return $instance;
 }
}
Description of Logic:


  • Declare the constructor "private" so this can not be called outside of class.As constructor can not be called out side of class so this class cannot be instantiated.
  • Now declared an static variable $instance that will hold the object. With the static data type $instance will hold the object till the class is alive.
  • Now i have made one method called getInstance(), it will check whether $instance already has some object, if it already has some object then it will return that object instance otherwise will assign an new object to this variable.
  • so only one instance at any time, now implement this class for database connection to avoid error like too many connection open.
?>

Saturday, May 22, 2010

Sort varchar numerically in Mysql

You may have faced this problem to sort data in ascending or descending order if datatype is varchar.
For example:
you have a table named "tablename" and a field name is "price" with data type varchar
and the values are as follows
0
100
200
50.5
150.
when you write sql like "SELECT * FROM tablename ORDER BY price ASC "
you will not be getting your result as per your query, so how will you sort your data as numerically.

Here is the way to sort data as numerically when data type is varchar
select * from `tablename` order by `fieldname` + 0 ASC