Pages

Wednesday, March 31, 2010

This is how we can use Control Flow Functions in Mysql.

Syntax: 


CASE value WHEN [compare_value] THEN result [WHEN [compare_value] THEN result ...] [ELSE result] END


CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END

Following is the Example for Switch Case query =>

SELECT u.`fname` as 'First Name' , u.`lname` as 'Last Name', u.`email` as 'Email', u.`tel_no` as 'Phone', u.country as 'Country', ug.start_date as 'Start Date', ug.end_date as 'End Date', (


CASE ug.end_date
WHEN '0000-00-00 00:00:00'
THEN 'active'
ELSE IF (
DATEDIFF(
now( ) , ug.end_date
) >0, 'inactive', 'active'
)
END
) AS
Status , ull.last_login_date as 'Last Login Date', ug.name AS
Product FROM `users` u, (



SELECT user_id, user_type_id, start_date, end_date, user_types.name
FROM user_groups, user_types
WHERE user_type_id
IN ( 4 )

AND user_groups.user_type_id = user_types.id
GROUP BY user_id
ORDER BY user_type_id DESC
)ug
LEFT JOIN (

SELECT user_id, max( login_time ) AS last_login_date
FROM user_login_log
GROUP BY user_id
) AS ull ON ug.user_id = ull.user_id
WHERE ug.user_id = u.id



Syntax:

mysql> SELECT IF(1>2,2,3);
-> 3
mysql>
SELECT IF(1<2,'yes','no');
-> 'yes'
mysql>
SELECT IF(STRCMP('test','test1'),'no','yes');



Following is the Example for IF-ELSE query =>


SELECT u.`id` AS 'User_Id', u.`fname` AS 'First_Name', u.`lname` AS 'Last_Name', u.`email` AS 'Email', domains.blog_id, domains.site, domains.status
FROM `users` AS u, `user_system` AS us, (


SELECT wp_blogs.blog_id, wp_blogs.domain AS sub_domain, IF(wp_blogs.public <> 0, 'active', 'inactive') AS status, wp_dm.domain AS site
FROM im500_live_wpmu.`wp_blogs` AS wp_blogs, im500_live_wpmu.`wp_domain_mapping` AS wp_dm
WHERE wp_blogs.blog_id = wp_dm.blog_id
AND wp_blogs.public = '1'
) AS domains


WHERE u.id = us.user_id
AND domains.sub_domain LIKE concat( u.username, '.%' )
AND us.system_id =3





For more details: http://dev.mysql.com/doc/refman/5.5/en/control-flow-functions.html

Thursday, March 25, 2010

Export DB result in CSV file format

ini_set("display_errors",0);

include_once("inc.db_connect.php");
connect();

function exportMysqlToCsv($export = false,$filename = 'export.csv')
{
    $csv_terminated = "\n";
    $csv_separator = ",";
    $csv_enclosed = '"';
    $csv_escaped = "\\";
    $sql_query = " select c.fname, c.lname, c.email, co.product_name, co.status
from customers as c
JOIN customer_orders as co on c.id = co.customer_id  
where co.status = 'ABANDONED'
group by c.id";
 
    // Gets the data from the database
    $result = mysql_query($sql_query);
    $fields_cnt = mysql_num_fields($result);


    $schema_insert = '';

    for ($i = 0; $i < $fields_cnt; $i++)
    {
        $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
            stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
        $schema_insert .= $l;
        $schema_insert .= $csv_separator;
    } // end for

    $out = trim(substr($schema_insert, 0, -1));
    $out .= $csv_terminated;

  
    print("");
    print("
");
    print("
");
    // Format the data
    while ($row = mysql_fetch_array($result))
    {
     if($export)
     {
       $schema_insert = '';
       for ($j = 0; $j < $fields_cnt; $j++)
       {
           if ($row[$j] == '0' || $row[$j] != '')
           {

               if ($csv_enclosed == '')
               {
                   $schema_insert .= $row[$j];
               } else
               {
                   $schema_insert .= $csv_enclosed .
str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
               }
           } else
           {
               $schema_insert .= '';
           }

           if ($j < $fields_cnt - 1)
           {
               $schema_insert .= $csv_separator;
           }
       } // end for

       $out .= $schema_insert;
       $out .= $csv_terminated;
     }
     else{
     extract($row);
     print('
');
     }
    
    } // end while

    echo "
NameEmailProductStatus
' . $fname . ' ' . $lname . '' . $email . '' . $product_name . '' . $status . '
";
    if($export){
   header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
   header("Content-Length: " . strlen($out));
   // Output to browser with appropriate mime type, you choose ;)
   header("Content-type: text/x-csv");
   //header("Content-type: text/csv");
   //header("Content-type: application/csv");
   header("Content-Disposition: attachment; filename=$filename");
   echo $out;
   exit;
    }
}

use it in a following way.



if($_GET['export'']){
exportMysqlToCsv(true);
}
else{
exportMysqlToCsv();
}

?>




?>

Remove Unicode Characters Using PHP

function fix_ms_smart_quotes($string) {
#
$text = str_replace(
#
array("\xe2\x80\x98", "\xe2\x80\x99", "\xe2\x80\x9c", "\xe2\x80\x9d", "\xe2\x80\x93", "\xe2\x80\x94", "\xe2\x80\xa6"),
#
array("'", "'", '"', '"', '-', '--', '...'),
#
$string);
#
// Next, replace their Windows-1252 equivalents.
#
$text = str_replace(
#
array(chr(145), chr(146), chr(147), chr(148), chr(150), chr(151), chr(133)),
#
array("'", "'", '"', '"', '-', '--', '...'),
#
$text);
#
return $text;
#
}


function removeHTMLTags($content){

$content = mb_convert_encoding($content, 'UTF-8', 'HTML-ENTITIES');
$content = fix_ms_smart_quotes($content);
$content = htmlspecialchars_decode($content);
$content = html_entity_decode($content);
$content = stripslashes($content);

return $content;
}

Friday, March 19, 2010

The Java Object Oriented Programming

The Java programming language is a high-level language can be defined with the follwing terms.




Simple
Architecture neutral
Object orientedPortable

Distributed

High performance

Multithreaded

Robust

Dynamic

Secure

Object-Oriented Programming Concepts:

What Is an Object?
Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your car.
Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). cars also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.

Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?". Make sure to write down your observations. As you do, you'll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.



Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.

By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the car only has 5 gears, a method to change gears could reject any value that is less than 1 or greater than 5.
Bundling code into individual software objects provides a number of benefits, including:

Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.
Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.
Code re-use: If an object already exists, you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.
Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other Cars in existence, all of the same make and model. Each Car was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your car is an instance of the class of objects known as Car. A class is the blueprint from which individual objects are created.
The following Car class is one possible implementation of a Car:


class Car{

int cadence = 0;
int speed = 0;
int gear = 1;

void changeCadence(int newValue) {
cadence = newValue;
}

void changeGear(int newValue) {
gear = newValue;
}

void speedUp(int increment) {
speed = speed + increment;
}

void applyBrakes(int decrement) {
speed = speed - decrement;
}

void printStates() {
System.out.println("cadence:"+cadence+" speed:"+speed+" gear:"+gear);
}
}
The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of Car objects. The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world.

Friday, March 12, 2010

Writting .htaccess file









.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

Further note that Apache must look for .htaccess files in all higher-level directories, in order to have a full complement of directives that it must apply. (See section on how directives are applied.) Thus, if a file is requested out of a directory /www/htdocs/example, Apache must look for the following files:

/.htaccess
/www/.htaccess
/www/htdocs/.htaccess
/www/htdocs/example/.htaccess

htaccess is useful for the following - (find code snippets below)
  • Indexes
  • Permission
  • Redirect
  • Error Handling
  • Cache Handling


Full article can be read from here <http://httpd.apache.org/docs/1.3/howto/htaccess.html>

Enable Directory Browsing
Options +Indexes
## block a few types of files from showing
IndexIgnore *.wmv *.mp4 *.avi

Disable Directory Browsing
Options All -Indexes

Customize Error Messages
ErrorDocument 403 /forbidden.html
ErrorDocument 404 /notfound.html
ErrorDocument 500 /servererror.html

Change Default Page (order is followed!)
DirectoryIndex myhome.htm index.htm index.php

Block Users from accessing the site

order deny,allow
deny from 202.54.122.33
deny from 8.70.44.53
deny from .spammers.com
allow from all

Allow only LAN users
order deny,allow
deny from all
allow from 192.168.0.0/24

Redirect Visitors to New Page/Directory

Allow only access via www link
RewriteCond %{HTTP_HOST} !^www.domainname.com [NC]
RewriteRule ^(.*)$  http://www.domainname.com/$1 [QSA,L,R=301]


Block site from specific referrers
RewriteEngine on
RewriteCond %{HTTP_REFERER} site-to-block\.com [NC]
RewriteCond %{HTTP_REFERER} site-to-block-2\.com [NC]
RewriteRule .* - [F]

Block Hot Linking/Bandwidth hogging
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ - [F]
Want to show a “Stealing is Bad” message too?
Add this below the Hot Link Blocking code:
RewriteRule \.(gif|jpg)$ http://www.mydomain.com/dontsteal.gif [R,L]
Stop .htaccess (or any other file) from being viewed

order allow,deny
deny from all

Avoid the 500 Error
# Avoid 500 error by passing charset
AddDefaultCharset utf-8

Enable Gzip – Save Bandwidth
# BEGIN GZIP

AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript

# END GZIP

Set an Expires header and enable Cache-Control

  ExpiresActive On
  ExpiresDefault "access plus 1 seconds"
  ExpiresByType text/html "access plus 7200 seconds"
  ExpiresByType image/gif "access plus 518400 seconds"
  ExpiresByType image/jpeg "access plus 518400 seconds"
  ExpiresByType image/png "access plus 518400 seconds"
  ExpiresByType text/css "access plus 518400 seconds"
  ExpiresByType text/javascript "access plus 216000 seconds"
  ExpiresByType application/x-javascript "access plus 216000 seconds"



  # Cache specified files for 6 days
  css|swf)$">
  Header set Cache-Control "max-age=518400, public"
  

  # Cache HTML files for a couple hours
  
  Header set Cache-Control "max-age=7200, private, must-revalidate"
  

  # Cache PDFs for a day
  
  Header set Cache-Control "max-age=86400, public"
  

  # Cache Javascripts for 2.5 days
  
  Header set Cache-Control "max-age=216000, private"
  

Thursday, March 11, 2010

Zend Framework 1.8 Web Application Development review


Zend Framework 1.8 Web Application Development

It took me a bit more time than I though to do this (one of the reasons will become clear soon) but here it finally comes.
I think it is a great book for somebody who is somewhat acquainted with Zend Framework and wants to get really good at working with it. It covers a lot of ground, so if you never worked with ZF before you might be a bit overwhelmed by the amount of stuff going on (then again, maybe I am underestimating you :) ), so you may want either skip some detail to return to it later when the need arises or have a run through a very basic tutorial for getting to know how the framework works before. The book itself has the basic startup section but I feel for a complete newbie it still might be a bit tough to keep up with the amount of the material in the book. That of course will come handy later when you got the basics figured out.
I personally am a big fan of learning by example and I think one line of code is often worth a hundred words, so I was really pleased that this book is based on building a complete application and comes with full application code to accompany it. The application is a storefront with an admin interface, so it covers most of the common tasks in a typical PHP application.
While it means that on the road there were certain decisions to be taken, and certain ways of doing things will be chosen over certain others, the author clearly identifies the decision points and explains the reasons – i.e. why certain things go to a model and not controller, why this extension point and not that one is used, etc. ZF has a very rich set of features, so there’s no single “right way” to do all things – but the book certainly shows you one of the ways to reach the complete and nicely structured application.
I actually took a bit of an experiment – as I was at the time building some ZF-based application, I decided to use the book as a first reference for any question that I needed with the app. I am pleased to report that the book indeed proved very helpful and I was able to find most of the advanced topics – like the use of ACLs, interactions between forms, views and decorators, modifying the behavior of the standard ZF classes, etc. – answered in the book and demonstrated in the code. The author successfully avoided the temptation to quote the manual extensively and instead picks up where the manual leaves off – i.e. how does one use stuff that the manual describes in practice.
The book also covers – albeit somewhat lightly – the topic that is neglected by so many other ZF books – namely testing. It shows how to setup the test environment and how to execute some basic application tests. Ideally, I would like the topic of tests to be much more prominent and featured as something parallel to development and not something you do after (though I know that’s how it rally happens many times ;) ) – but I know there’s only so much you can put into one book :)