Saturday, September 1, 2012

Generate random code using PHP


Below is the function to generate a random code(alpha-numeric) using PHP. We can use the below function for generating a coupon code (or) verification code (or) affiliate code for the people.



function generate_random_code( $size )
{
        $list_chars = array_merge(range('A','Z'), range(0,9));
      
        $referal_code = '';
      
        for($i=0;$i<=$size;$i++)
        {
            $referal_code .= $list_chars[mt_rand(0, count($list_chars)-1)];
        }
      
        return $referal_code;
      
}


$size  => Length of the random code to be generated. 

Wednesday, June 13, 2012

Calculate time difference using PHP


 function get_time_difference_php($created_time)
 {
        date_default_timezone_set('Asia/Calcutta'); //Change as per your default time
        $str = strtotime($created_time);
        $today = strtotime(date('Y-m-d H:i:s'));
        
        // It returns the time difference in Seconds...
        $time_differnce = $today-$str;
        
        // To Calculate the time difference in Years...
        $years = 60*60*24*365;
        
        // To Calculate the time difference in Months...
        $months = 60*60*24*30;
        
        // To Calculate the time difference in Days...
        $days = 60*60*24;
        
        // To Calculate the time difference in Hours...
        $hours = 60*60;
        
        // To Calculate the time difference in Minutes...
        $minutes = 60;

        if(intval($time_differnce/$years) > 1)
        {
            return intval($time_differnce/$years)." years ago";
        }else if(intval($time_differnce/$years) > 0)
        {
            return intval($time_differnce/$years)." year ago";
        }else if(intval($time_differnce/$months) > 1)
        {
            return intval($time_differnce/$months)." months ago";
        }else if(intval(($time_differnce/$months)) > 0)
        {
            return intval(($time_differnce/$months))." month ago";
        }else if(intval(($time_differnce/$days)) > 1)
        {
            return intval(($time_differnce/$days))." days ago";
        }else if (intval(($time_differnce/$days)) > 0) 
        {
            return intval(($time_differnce/$days))." day ago";
        }else if (intval(($time_differnce/$hours)) > 1) 
        {
            return intval(($time_differnce/$hours))." hours ago";
        }else if (intval(($time_differnce/$hours)) > 0) 
        {
            return intval(($time_differnce/$hours))." hour ago";
        }else if (intval(($time_differnce/$minutes)) > 1) 
        {
            return intval(($time_differnce/$minutes))." minutes ago";
        }else if (intval(($time_differnce/$minutes)) > 0) 
        {
            return intval(($time_differnce/$minutes))." minute ago";
        }else if (intval(($time_differnce)) > 1) 
        {
            return intval(($time_differnce))." seconds ago";
        }else
        {
            return "few seconds ago";
        }
  }

Tuesday, June 5, 2012

Difference between current date and past date using MySQL


Below is the function to get the time difference between Current date and the past date using MySQL. Mainly it can be used where we want to display the time gap between the registration of the user.


function getTimeDifference($created_since)
{
            $datediffquery = mysql_query  ("SELECT CASE WHEN TIMESTAMPDIFF(YEAR ,'".$created_since."', NOW()) > 1 THEN CONCAT(TIMESTAMPDIFF(YEAR ,'".$created_since."', NOW()), ' years ago')
                                                WHEN TIMESTAMPDIFF(YEAR ,'". $created_since."', NOW()) > 0 THEN CONCAT(TIMESTAMPDIFF(YEAR ,'". $created_since ."', NOW()), ' year ago')
                                                WHEN TIMESTAMPDIFF(MONTH ,'".$created_since."', NOW()) > 1 THEN CONCAT(TIMESTAMPDIFF(MONTH ,'".$created_since."', NOW()), ' months ago')
                                                WHEN TIMESTAMPDIFF(MONTH ,'".$created_since."', NOW()) > 0 THEN CONCAT(TIMESTAMPDIFF(MONTH ,'".$created_since."', NOW()), ' month ago')
                                                WHEN TIMESTAMPDIFF(DAY ,'".$created_since."', NOW()) > 1 THEN CONCAT(TIMESTAMPDIFF(DAY ,'".$created_since."', NOW()), ' days ago')
                                                WHEN TIMESTAMPDIFF(DAY ,'".$created_since."', NOW()) > 0 THEN CONCAT(TIMESTAMPDIFF(DAY ,'".$created_since."', NOW()), ' day ago')
                                                WHEN TIMESTAMPDIFF(HOUR ,'".$created_since."', NOW()) > 1 THEN CONCAT(TIMESTAMPDIFF(HOUR ,'".$created_since."', NOW()), ' hours ago')
                                                WHEN TIMESTAMPDIFF(HOUR ,'".$created_since."', NOW()) > 0 THEN CONCAT(TIMESTAMPDIFF(HOUR ,'".$created_since."', NOW()), ' hour ago')
                                                WHEN TIMESTAMPDIFF(MINUTE ,'".$created_since."', NOW()) > 1 THEN CONCAT(TIMESTAMPDIFF(MINUTE ,'".$created_since."', NOW()), ' minutes ago')
                                                WHEN TIMESTAMPDIFF(MINUTE ,'".$created_since."', NOW()) > 0 THEN CONCAT(TIMESTAMPDIFF(MINUTE ,'".$created_since."', NOW()), ' minute ago')
                                                WHEN TIMESTAMPDIFF(SECOND ,'".$created_since."', NOW()) > 1 THEN CONCAT(TIMESTAMPDIFF(SECOND ,'".$created_since."', NOW()), ' seconds ago')
                                            END
                                        AS total_days");
            
            $row = mysql_fetch_assoc($datediffquery);
            
            return $row['total_days'];
        }

Friday, May 25, 2012

Calculate time difference between two dates using PHP

Below is the PHP function to calculate the time difference between current date and the given date.

It will returns in Seconds, minutes, months (or) years based on the time difference.

And it can be used to calculate the time difference between two dates by changing the $today with the date which you want to pass.


function get_time_difference_php($created_time)
    {
        date_default_timezone_set('Asia/Calcutta');
        $str = strtotime($created_time);
        $today = strtotime(date('Y-m-d H:i:s'));
        
        // It returns the time difference in Seconds...
        $time_differnce = $today-$str;
        
        // To Calculate the time difference in Years...
        $years = 60*60*24*365;
        
        // To Calculate the time difference in Months...
        $months = 60*60*24*30;
        
        // To Calculate the time difference in Days...
        $days = 60*60*24;
        
        // To Calculate the time difference in Hours...
        $hours = 60*60;
        
        // To Calculate the time difference in Minutes...
        $minutes = 60;

        if(intval($time_differnce/$years) > 1)
        {
            return intval($time_differnce/$years)." years ago";
        }else if(intval($time_differnce/$years) > 0)
        {
            return intval($time_differnce/$years)." year ago";
        }else if(intval($time_differnce/$months) > 1)
        {
            return intval($time_differnce/$months)." months ago";
        }else if(intval(($time_differnce/$months)) > 0)
        {
            return intval(($time_differnce/$months))." month ago";
        }else if(intval(($time_differnce/$days)) > 1)
        {
            return intval(($time_differnce/$days))." days ago";
        }else if (intval(($time_differnce/$days)) > 0) 
        {
            return intval(($time_differnce/$days))." day ago";
        }else if (intval(($time_differnce/$hours)) > 1) 
        {
            return intval(($time_differnce/$hours))." hours ago";
        }else if (intval(($time_differnce/$hours)) > 0) 
        {
            return intval(($time_differnce/$hours))." hour ago";
        }else if (intval(($time_differnce/$minutes)) > 1) 
        {
            return intval(($time_differnce/$minutes))." minutes ago";
        }else if (intval(($time_differnce/$minutes)) > 0) 
        {
            return intval(($time_differnce/$minutes))." minute ago";
        }else if (intval(($time_differnce)) > 1) 
        {
            return intval(($time_differnce))." seconds ago";
        }else
        {
            return "few seconds ago";
        }
    }

Saturday, April 21, 2012

Load file using MySQL

Most of the Programmers will be using the normal file operations to import a CSV file, we can use MySQL Load file too import a CSV to database table.

Below is the syntax to import the file to DB

LOAD DATA INFILE "/home/mysql/data/my_table_data.csv" INTO TABLE dummy_table FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';

Wednesday, March 7, 2012

Retrieve the XML node value using PHP

When we want to read the XML tag value, we may use simple_xml_load or DOMdocument to read it and will get the particular node value. Below is the simple PHP function to retrieve the XML node value by passing the XML as string and passing the starting XML tag and ending XML tag.


function get_value_by_tag_Name( $str, $s_tag, $e_tag)
{
$s = strpos( $str,$s_tag) + strlen( $s_tag);
$e = strlen( $str);
$str= substr($str, $s, $e);
$e = strpos( $str,$e_tag);
$str= substr($str,0, $e);
$str= substr($str,0, $e);
return  $str;
}

Here $str is the XML which we are passing as a string, $s_tag is the Starting tag(Ex: '<EmployeeDetails'>) and $e_tag is the ending tag (Ex: '</EmployeeDetails>'). By passing the values it returns the node value.

So, it reduces the parsing XML and DOM Document steps.

Thursday, January 26, 2012

Difference between MyISAM and InnoDB MySQL

InnoDB and MyISAM most popular storage engines in MySQL & also mostly used storage engine is the MyISAM. But most of them don't know the importance of InnoDB.

Below are the basic differences of MyISAM and InnoDB.
  1. InnoDB supports transactions which is not supported by tables which use MyISAM storage engine. Transaction is nothing but a set of MySQL queries run in an Stored Procedure as shown (BEGIN TRANSACTION ......SET of QUERIES ......END). 
  2. InnoDB has row-level locking, relational integrity i.e. supports foreign key relationship between tables, which is not possible in MyISAM.
  3. InnoDB ‘s performance for higher volume data which cannot be beaten by any other storage engines available.
Tables created in MyISAM are known to be much faster compared to tables in InnoDB. But since InnoDB supports volume, transactions, integrity it’s always a better option when we are dealing with a larger database.

Find the nth highest Salary in a table using MySQL

To find the nth highest salary or highest score in a table, below is the query to find out.

SELECT * FROM employee a WHERE n = (SELECT COUNT(*) FROM employee b WHERE a.salary <= b.salary) ;

'n'  --> By replacing n with the required value we can get the second, third, fourth highest and so on..


Tuesday, January 24, 2012

jQuery Form Validation

Tired of validating the form using javascript. Here is the code to validate the form using jQuery.


  function submit_form()
{
var formElements = $('#form_name .required'); // Reading all elements in the form which are having class as required

var error = 0;

formElements.each(function() { // Looping all the elements which are having the class name as required...
if($(this).val() == "") {  // Checking the value of the field
                                                // Showing the border color as red if the field is empty
$(this).css('border','1px solid red');
error++;
} else {
                                                // removing the border if the field has the value....
$(this).css('border','none');
}
});
}

Use the submit_form function in onsubmit of the form.

The fields in the form which need to be validated should be given as below.

<input type="text" name="field_name" class="required" />

If we add the class required for the textbox, it validates otherwise it doesnot validate the textbox.


Replace the contents in MySQL data

Below is the Query to replace the data with the required data in the column fields for the Table.

UPDATE `table_name` SET `column_name` = REPLACE(`column_name`,'search string','replace string');

table_name --> The table data which you want to change

column_name --> Particular column of the table


Thursday, January 12, 2012

How PHP Script runs


PHP is a web scripting language which is platform independent.

Below picture shows you how the php script executes when you enter the URL of the page.