Tuesday 11 December 2012

SQL_CALC_FOUND_ROWS / FOUND_ROWS() does not work in PHP

$s1 = $sql->query('select SQL_CALC_FOUND_ROWS * from db limit 0, 3');
$s2 = $sql->query('select FOUND_ROWS()');
if($row = $s2->fetch_row()) printf('%d/%d', $s1->num_rows, $row[0]);
Sometime, when we run something analogous to above example on the mysql command line, it would work; but running it from php, it failed. The second query has to "know about" the first one, so for some reason its persistence/memory linking the two queries was getting messed up by the php.

(It turns out that Wordpress uses this type of query to do its pagination - so our larger problem was that the pagination in a wordpress install suddenly stopped working when we moved to php 5.2.6 ... eventually tracked it down to the FOUND_ROWS()).

Just for the sake of posting for people who may run into this in the future... for me it was the php setting "mysql.trace_mode" - this defaulted "on" in 5.2.6 instead of "off" like previously, and for some reason prevents the FOUND_ROWS() from working.

As a "fix", we could either put this in every php page (actually, in a common "include"):
ini_set("mysql.trace_mode", "0");
or add this to the .htaccess:
php_value mysql.trace_mode "0"

Friday 16 November 2012

Install SQLYog with Wine in Ubuntu 12.04

First, download the SQLYog from here. Before that, make sure that you have already installed the wine into your machine, if you don't know how to install wine, refer to this link.

Afterwards, run the following command in terminal (use CTRL+ALT+T to open terminal).

wine /home/rc/Downloads/SQLYog-10.4.0-2-trial.exe 

Then, it should execute the .exe file, and just follow the SQLYog installation as like normally.
However, if you stuck with some error like below;
  wine is not owned by you , err msg.....

In that case, just run the below command (where rc is the shell user). Then run the above command again once the below command is successfully executed.

sudo chown -R rc:rc ~/.wine 


Enjoy !!!

Install Wine in Ubuntu 12.04, or Linux or Linux Mint


Wine enables Linux, Mac, FreeBSD, and Solaris users to run Windows applications without a copy of Microsoft Windows. Wine is free software under constant development. Other platforms may benefit as well. 
Wine 1.5.4 has just been released and this brief tutorial is going to show you how to install it in Ubuntu 12.04. Wine is an open source application which lets you install and run programs designed for Microsoft Windows systems in Linux systems. Not all your Windows programs will run with Wine, but many popular software that you depend on which run in Windows will run perfectly in Ubuntu using Wine.
With this release, comes many enhancements and bug fixes from the previous released version. You can now run Microsoft Office 2003, 2007 properly, Adobe Premier Pro, support for .NET 4.0 and many other software. For a more detailed release note, click here.
To get started, Open the Terminal ( can use press Ctrl+Alt+T on your keyboard to open Terminal). When it opens, run the commands below to add Wine PPA.

sudo add-apt-repository ppa:ubuntu-wine/ppa
sudo apt-get install winetricks

Finally, run the commands below to update your system and install Wine 1.5
sudo apt-get update && sudo apt-get install wine1.5

Thursday 15 November 2012

Ubuntu: Upgrade error due to another package management application running


Ubuntu: Upgrade error due to another package management application running 


Please, try some of these steps in order:
If you haven't already done so reboot your machine and try running the update again.
Try to run one of the below command or all on command line as;
sudo apt-get clean
sudo do-release-upgrade
sudo rm /var/lib/dpkg/lock 
Manually remove the lock file and try running the update again.

Thursday 4 October 2012

Difference between single and double quotes in PHP


Well first of all, single quotes are much more efficient than double quotes, which is shown in the results from a simple test, which you can find here:http://phpbar.isgreat.org/viewtopic.php?f=2&t=56

So, there obviously is a difference between them, but what is it?

Simply put, single quotes are completely static, where as double quotes are dynamic with changing values.
For example:
CODE: SELECT ALL
$someVar = 'more Text';
echo 'Some Text $someVar';

will output
CODE: SELECT ALL
Some Text $someVar


However, the same example but with double quotes:
CODE: SELECT ALL
$someVar = 'more Text';
echo "Some Text $someVar";

will output
CODE: SELECT ALL
Some Text more Text


Obviously single quotes will have a better efficiency than double quotes, because in single quotes, php does not process anything within it, where as with double quotes, php is constantly looking through the string for variable names to check and call.

So how do we use this new knowledge to our advantage?

Well, since single quotes do not process variables how do we add variables to the string?
Well if you haven't figured it out, we simply use the string addition character.
For example:
CODE: SELECT ALL
$str = 'more text';
echo 'some text and '.$str;

It is a bit of a hassle, but like in most things about programming, its usually efficiency vs programing time. A classic example of this is, C++ vs C#.

However, when using single quotes, depending on your php version, '\n' will output \n, so you will occasionally have to use, "\n" or PHP_EOL

well, if you still want to use double quotes, because your lazy :D
there are still times when you may find it easier to use single quotes. for example, if you are outputting static text like HTML that has mass amounts of double quotes in it. Or if you want to output the name of a variable.

Of course, you could still do
CODE: SELECT ALL
echo "$"."varname";

instead of
CODE: SELECT ALL
echo '$varname';

but in that case you might as well just use single quotes.

---
So yes, there is a huge difference between the single and double quotes other than simple quote escaping.

Well, i hope this helps you a lot, and it is best to try to be as efficient as possible, ESPECIALLY when using loops. so its alright to use double quotes when your lazy, but be sure to avoid them when writing large loops, or commonly used functions.

Enjoy

Sunday 9 September 2012

Joomla 2.5 versions issues while upgrade. Joomla include/framework.php line 42 or line 35 error.


2.5.1 Installation Parse error: syntax error .. on line 35
Had the same error after using jUpgrade to move a 1.5.x site to 2.5.1. which is hosted by 1and1. Everything tested fine after the install and when I moved the jUpgrade folder to the correct folder to make the site live I got a similar error.

Fixed it by changing the htaccess.txt file to .htaccess and adding the following line
//Code:
# Line added to force register_globals OFF
AddType x-mapp-php5 .php
Source: Read More

Thursday 6 September 2012

PHP Function To List Months Names and Years


/**
 * Return the List of all the 12 months name as per requested.
 * @param char $monthType The month format type you want month to be display.
 * @return array:string Return the list of months.
 */
function get_all_months($monthType = 'F')
{
 $months = array();
 
 for ( $m=1; $m<=12; $m++ )
 {
  $months[$m] = date($monthType, mktime(0,0,0,$m,1,2000));;
 }
 
 return $months;
}

/**
 * Return the List of all the year name as per requested.
 * @param char $yearType The Year format type you want year to be display.
 * @return array:string Return the list of month for upto 2020 years which you can change as per your needs.
 */
function get_all_years($yearType = 'Y')
{
 $months = array();
 $yearLength = 20; // This is the limit for year to be display for next 20 years.
 
 for ( $y=11; $y<=$yearLength; $y++ )
 {
  $months[$y] = date($yearType, mktime(0,0,0,1,1,$y));;
 }

 return $months;
}

Wednesday 5 September 2012

Set variables which could cause the TCPDF to generate PDF correctly


// These below are variables which could cause the TCPDF to generate PDF correctly. // So, please check the tcpdf configuration and set the below variables if necessary.
/* Increase the memory limit for the PDF. */
ini_set('memory_limit', '256M'); 
ini_set('safe_mode', 0);
ini_set('allow_url_fopen', 1);

Wednesday 15 August 2012

Create Zip File for Multiple files to be downloadable in Codeigniter

define('ROOT_DOWNLOAD_FOLDER_PATH', $_SERVER['DOCUMENT_ROOT']."_files/_downloads/");

function CreateZipFile($zip_folder_name)
{
 $directoryToZip = ROOT_DOWNLOAD_FOLDER_PATH; // This will zip all the file(s) in this present working directory
 $outputDir = ROOT_DOWNLOAD_FOLDER_PATH; //Replace "/" with the name of the desired output directory.
 $this->load->library('ZipFile');
  
 //$this->createzipfile->get_files_from_folder($outputDir, $zip_folder_name.'-');
 $this->zipfile->get_files_from_folder($directoryToZip, '');
 
 //Code toZip a directory and all its files/subdirectories
 $this->zipfile->zipDirectory($directoryToZip, $outputDir);
 
 $fileName = $outputDir.$zip_folder_name.'.zip';

 $fd = fopen ($fileName, 'wb');
 $out = fwrite ($fd, $this->zipfile->getZippedfile());
  
 $this->zipfile->forceDownload($fileName);
 
 @unlink($fileName);
 fclose($fd);
 
 /* Empty directory and remove directory. */
 $directoryToZipPath = $directoryToZip.$zip_folder_name;
 unlinkFolderFiles($directoryToZipPath);
 removeDir($directoryToZipPath);

 exit;
}

$timestamp = date('Y.m.d.h.i.s');
$timestamp = '2012.08.15.12.45.46';
$zip_folder_name = 'Flubit.Inv.All.'.$timestamp;
// For the ZipFile.php, save the below ZipFile.php file content into application/libaries/ZipFile.php
/**
 * Class to dynamically create a zip file (archive) of file(s) and/or directory
 *
 * @author Rochak Chauhan  www.rochakchauhan.com
 * @package CreateZipFile
 * @see Distributed under "General Public License"
 * 
 * @version 1.0
 */

class ZipFile {

 public $compressedData = array();
 public $centralDirectory = array(); // central directory
 public $endOfCentralDirectory = "\x50\x4b\x05\x06\x00\x00\x00\x00"; //end of Central directory record
 public $oldOffset = 0;
 
 function get_files_from_folder($directory, $put_into) {
  if ($handle = opendir($directory)) {
   while (false !== ($file = readdir($handle))) {
    if (is_file($directory.$file)) {
     $fileContents = file_get_contents($directory.$file);
     $this->addFile($fileContents, $put_into.$file);
    } elseif ($file != '.' and $file != '..' and is_dir($directory.$file)) {
     $this->addDirectory($put_into.$file.'/');
     $this->get_files_from_folder($directory.$file.'/', $put_into.$file.'/');
    }
   }
  }
  closedir($handle);
 }
 
 /**
  * Function to create the directory where the file(s) will be unzipped
  *
  * @param string $directoryName
  * @access public
  * @return void
  */ 
 public function addDirectory($directoryName) {
  $directoryName = str_replace("\\", "/", $directoryName);
  $feedArrayRow = "\x50\x4b\x03\x04";
  $feedArrayRow .= "\x0a\x00";
  $feedArrayRow .= "\x00\x00";
  $feedArrayRow .= "\x00\x00";
  $feedArrayRow .= "\x00\x00\x00\x00";
  $feedArrayRow .= pack("V",0);
  $feedArrayRow .= pack("V",0);
  $feedArrayRow .= pack("V",0);
  $feedArrayRow .= pack("v", strlen($directoryName) );
  $feedArrayRow .= pack("v", 0 );
  $feedArrayRow .= $directoryName;
  $feedArrayRow .= pack("V",0);
  $feedArrayRow .= pack("V",0);
  $feedArrayRow .= pack("V",0);
  $this->compressedData[] = $feedArrayRow;
  $newOffset = strlen(implode("", $this->compressedData));
  $addCentralRecord = "\x50\x4b\x01\x02";
  $addCentralRecord .="\x00\x00";
  $addCentralRecord .="\x0a\x00";
  $addCentralRecord .="\x00\x00";
  $addCentralRecord .="\x00\x00";
  $addCentralRecord .="\x00\x00\x00\x00";
  $addCentralRecord .= pack("V",0);
  $addCentralRecord .= pack("V",0);
  $addCentralRecord .= pack("V",0);
  $addCentralRecord .= pack("v", strlen($directoryName) );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("V", 16 );
  $addCentralRecord .= pack("V", $this->oldOffset );
  $this->oldOffset = $newOffset;
  $addCentralRecord .= $directoryName;
  $this->centralDirectory[] = $addCentralRecord;
 }

 /**
  * Function to add file(s) to the specified directory in the archive 
  *
  * @param string $directoryName
  * @param string $data
  * @return void
  * @access public
  */ 
 public function addFile($data, $directoryName)   {
  $directoryName = str_replace("\\", "/", $directoryName);
  $feedArrayRow = "\x50\x4b\x03\x04";
  $feedArrayRow .= "\x14\x00";
  $feedArrayRow .= "\x00\x00";
  $feedArrayRow .= "\x08\x00";
  $feedArrayRow .= "\x00\x00\x00\x00";
  $uncompressedLength = strlen($data);
  $compression = crc32($data);
  $gzCompressedData = gzcompress($data);
  $gzCompressedData = substr( substr($gzCompressedData, 0, strlen($gzCompressedData) - 4), 2);
  $compressedLength = strlen($gzCompressedData);
  $feedArrayRow .= pack("V",$compression);
  $feedArrayRow .= pack("V",$compressedLength);
  $feedArrayRow .= pack("V",$uncompressedLength);
  $feedArrayRow .= pack("v", strlen($directoryName) );
  $feedArrayRow .= pack("v", 0 );
  $feedArrayRow .= $directoryName;
  $feedArrayRow .= $gzCompressedData;
  $feedArrayRow .= pack("V",$compression);
  $feedArrayRow .= pack("V",$compressedLength);
  $feedArrayRow .= pack("V",$uncompressedLength);
  $this->compressedData[] = $feedArrayRow;
  $newOffset = strlen(implode("", $this->compressedData));
  $addCentralRecord = "\x50\x4b\x01\x02";
  $addCentralRecord .="\x00\x00";
  $addCentralRecord .="\x14\x00";
  $addCentralRecord .="\x00\x00";
  $addCentralRecord .="\x08\x00";
  $addCentralRecord .="\x00\x00\x00\x00";
  $addCentralRecord .= pack("V",$compression);
  $addCentralRecord .= pack("V",$compressedLength);
  $addCentralRecord .= pack("V",$uncompressedLength);
  $addCentralRecord .= pack("v", strlen($directoryName) );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("V", 32 );
  $addCentralRecord .= pack("V", $this->oldOffset );
  $this->oldOffset = $newOffset;
  $addCentralRecord .= $directoryName;
  $this->centralDirectory[] = $addCentralRecord;
 }

 /**
  * Function to return the zip file
  *
  * @return zipfile (archive)
  * @access public
  * @return void
  */
 public function getZippedfile() {
  $data = implode("", $this->compressedData);
  $controlDirectory = implode("", $this->centralDirectory);
  return
  $data.
  $controlDirectory.
  $this->endOfCentralDirectory.
  pack("v", sizeof($this->centralDirectory)).
  pack("v", sizeof($this->centralDirectory)).
  pack("V", strlen($controlDirectory)).
  pack("V", strlen($data)).
  "\x00\x00";
 }

 /**
  *
  * Function to force the download of the archive as soon as it is created
  *
  * @param archiveName string - name of the created archive file
  * @access public
  * @return ZipFile via Header
  */
 public function forceDownload($archiveName) {
  if(ini_get('zlib.output_compression')) {
   ini_set('zlib.output_compression', 'Off');
  }

  // Security checks
  if( $archiveName == "" ) {
   echo "Public Photo Directory - Download 
ERROR: The download file was NOT SPECIFIED."; exit; } elseif ( ! file_exists( $archiveName ) ) { echo "Public Photo Directory - Download
ERROR: File not found."; exit; } header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); header("Content-Type: application/zip"); header("Content-Disposition: attachment; filename=".basename($archiveName).";" ); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".filesize($archiveName)); readfile("$archiveName"); } /** * Function to parse a directory to return all its files and sub directories as array * * @param string $dir * @access protected * @return array */ protected function parseDirectory($rootPath, $seperator="/"){ $fileArray=array(); $handle = opendir($rootPath); while( ($file = @readdir($handle))!==false) { if($file !='.' && $file !='..'){ if (is_dir($rootPath.$seperator.$file)){ $array=$this->parseDirectory($rootPath.$seperator.$file); $fileArray=array_merge($array,$fileArray); } else { $fileArray[]=$rootPath.$seperator.$file; } } } return $fileArray; } /** * Function to Zip entire directory with all its files and subdirectories * * @param string $dirName * @access public * @return void */ public function zipDirectory($dirName, $outputDir) { if (!is_dir($dirName)){ trigger_error("CreateZipFile FATAL ERROR: Could not locate the specified directory $dirName", E_USER_ERROR); } $tmp=$this->parseDirectory($dirName); $count=count($tmp); $this->addDirectory($outputDir); for ($i=0;$i<$count;$i++){ $fileToZip=trim($tmp[$i]); $newOutputDir=substr($fileToZip,0,(strrpos($fileToZip,'/')+1)); $outputDir=$outputDir.$newOutputDir; $fileContents=file_get_contents($fileToZip); $this->addFile($fileContents,$fileToZip); } } }
// The below are the basic File and Directory Related functions.
function createFile($filePath='')
{
 try {
  if (!empty($filePath))
  { 
   $ourFileHandle = fopen($filePath, 'w');
   fclose($ourFileHandle);
  }
  return true;
 }
 Catch(Exception $e){ return false; }
}

function unlinkFolderFiles($dir)
{
 $files = getFolderFiles($dir);

 foreach ($files as $file)
 {
  if(file_exists($dir.'/'.$file)) @unlink($dir.'/'.$file);
 }

 return true;
}

function getFolderFiles($dir)
{
 $files = '';
 $ffs = scandir($dir);

 foreach($ffs as $ff)
 {
  if($ff != '.' && $ff != '..')
  {
   $files[] = $ff;
  }
 }

 return $files;
}

function createDir($dir)
{
 if (!is_dir($dir)) {
  mkdir($dir);
 }

 return true;
}

function removeDir($dir)
{
 if (is_dir($dir)) {
  rmdir($dir);
 }
 
 return true;
}

Monday 6 August 2012

Convert the date time to timestamp and Compare the two datetime (dates) functions in Javascript.

Convert the date time to timestamp in Javascript. similar to strototime() function in php.
// Convert the date time to timestamp in Javascript. similar to strototime() function in php.
function convert_datetime_to_timestamp(date)
{
 var datetime = date.split(" ");
 date = datetime[0];
 time = datetime[1];

 d1 = date.split("-");
 y = d1[0];
 m = d1[1];
 d = d1[2];

 t1 = time.split(":");
 h = t1[0];
 i = t1[1];
 s = t1[2];

 //datetime = m + ' ' + d + ',' + y + ' ' + h + ':' + i + ':'+s;
var date = new Date(y, m, d, h, i, s, '0'); (works both on FireFox and Chrome Browers).
 
 return date.getTime();
}
// Compare the two datetime (dates) in Javascript.
/*  This below function compares two dates with a gap time as 6 Hours.
 @param date1 = '2012-08-06 14:9:19'
 @param date2 = '2012-08-06 20:9:19' 
 @return If errors found, return errors else null (if no errors) found. 
*/
function compare_two_dates(date1, date2)
{
 var error = '';
 
 if ( (date1 != "") || (date2 != "") )
 {
  // Check the dates time here;
  var minutes=1000*60;
  var hours=minutes*60;
  var days=hours*24;
  var years=days*365;
  
  now = new Date();
  current_time= now.getTime();
  
  // Check the dates time here;
  start_time= convert_datetime_to_timestamp(date1);
  expiry_time= convert_datetime_to_timestamp(date2);
  
  gap_hr = 6; // Minimum Gap between two dates is set as 6 Hrs. 
  gap_time= gap_hr*hours;
  diff_time= expiry_time - start_time;
  diff_mm= (diff_time)/minutes;
  diff_hr= Math.round(diff_time/hours);
  
  if ( (current_time >= start_time) && (current_time >= expiry_time))
   error = 'Date Available AND/OR Expiry time should be greater than current time.';

  else if ( (diff_time == 0) || (gap_time > diff_time) )
   error = 'Date Expires should be at least ' + gap_hr + ' hours greater than Date Available time.';
  
  //error = error + ' NowT: '+current_time+' DS: ' + start_time + ' DE: '+ expiry_time+' Diff: ' +diff_time+ ' DMM: ' + diff_mm+ ' DHR: '+diff_hr+' TG: '+gap_time;  
 }
 else {
  error =  'Enter both dates';
 }
 
 return error;
}

For more information about dates, please, check: JavaScript Date Object, JavaScript setDate() Method

Friday 27 July 2012

Increase Memory Limit to resolve Server error while generating PDF using third party library like TCPDF

When generating a PDF using TCPDF or any of the third party PDF libraries, and if you find the following issues while generating pdf;

------------------------------------------------------------------------------
Server error The website encountered an error while retrieving http://admincentre.flubstage.info/fcc/reporting/download_pdf_chain_report/01. It may be down for maintenance or configured incorrectly. Here are some suggestions: Reload this web page later. HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfil the request.
------------------------------------------------------------------------------

Solution: In that case, most probably, it would be memory limitation issue. So, you should increase the memory limit by adding the following code before the pdf generate code(the very beginning of the code).
/* Set the memory limit for the PDF. */
ini_set('memory_limit', '256M'); 

Tuesday 24 July 2012

Calculating the Standard Deviation using PHP

// Calculating the Standard Deviation.
private function standard_deviation($aValues, $bSample = false)
{
 $fMean = array_sum($aValues) / count($aValues);
 $fVariance = 0.0;
 foreach ($aValues as $i)
 {
  $fVariance += pow($i - $fMean, 2);
 }
 $fVariance /= ( $bSample ? count($aValues) - 1 : count($aValues) );
 return (float) sqrt($fVariance);
}

Friday 20 July 2012

Resize the image in various sizes using PHP

This is the mail resizing image function which actually resized the image based on provided parameter.
/**
 * This will resize the image into specific image sizes.
 * @param array $data:  'old_image_path' = full path of the old image which to be reszied;
 *  'new_image_path' = full path the new image to be created;
 *  'width' = New Width of the image;
 *  'height' = New Height of the image;
 *  (just for orignal) 'copy_original' = set 'true' if you like to just copy original image and you don't need to provide above 'width' and 'height', otherwise just ignore this.;
 *   
 * @return void;
 */
private function resizing_image($data)
{
 // Set copy_original=true, if you like to create original image.
 $create_original = isset($data['copy_original']) && ($data['copy_original']) ? true : false;
 
 //Set target path
 $target_path = $data['new_image_path'];
  
 //Get the width and height of upload image
 list($width, $height) = getimagesize($data['old_image_path']);
 
 if ($create_original) 
 {
  $bigwidth = $width;
  $bigheight = $height;
 }
 else 
 {
  $n_wight = $data['width'];
  $n_height = $data['height'];
  
  if ($width > $n_wight) {
   //If the width is greater than our maximum width preference, use the maximum width
   $newwidth = $n_wight;
   //Set new ratios for width and height
   $newheight = ($newwidth/$width) * $height;
   $bigwidth = $newwidth;
   $bigheight = $newheight;
  } else {
   //If width is less than our maximum, use that value (so as not to pixelate the image)
   $bigwidth = $width;
   $bigheight = $height;
  }
   
  if ($bigheight > $n_height) {
   //If the height is greater than our maximum height preference, use the maximum height
   $newheight = $n_height;
   //Set new ratios for width and height
   $newwidth = ($newheight/$bigheight) * $bigwidth;
   $bigwidth = $newwidth;
   $bigheight = $newheight;
  }
 }
 
 //Initiate image magick class
 $im = new Imagick();
 //Get image
 $im->readImage( $data['old_image_path'] );
 //Create thumbnail image
 $im->thumbnailImage( $bigwidth, $bigheight );
 //Write to file
 $im->writeImage( $target_path );
 /*
 echo '

Original Image Size: Width-'. $width. ' Height:-'.$height;
 echo '
New Image Size: Width-'. $bigwidth. ' Height:-'.$bigheight;
 echo '
'.$target_path;
 */
 //Destroy temp
 $im->destroy();
}

This function is to resize image in various sizes
// This function is to resize image in various sizes
private function resize_image($product_id, $old_image_path)
{
 define('PATH_RESIZED_PRODUCT_IMAGE', "/home/admin/assets/products/");
 $new_path = PATH_RESIZED_PRODUCT_IMAGE; //"";
  
 $product_id = 23;
 $old_image_path = 'http://ecx.images-amazon.com/images/I/81RXp-hIaNL._AA1500_.jpg';
 //$old_image_path = 'http://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/280px-PNG_transparency_demonstration_1.png';
 
 /** Get File Extension. */
 $path_info = pathinfo($old_image_path);
 $ext = $path_info['extension'];
 
 // Create Thumbnail (max 40px by 40px)
 $new_image_path = $new_path.'t_'.$product_id.'.'.$ext; // building the new targeted file path including new filename ("";) 
 $data = array('old_image_path'=>$old_image_path, 'new_image_path'=>$new_image_path, 'width'=>40, 'height'=>40);
 $this->resizing_image($data);
 
 // Create Standard (max 310px by 235px)
 $new_image_path = $new_path.'s_'.$product_id.'.'.$ext; // building the new targeted file path including new filename ("";)
 $data = array('old_image_path'=>$old_image_path, 'new_image_path'=>$new_image_path, 'width'=>310, 'height'=>235);
 $this->resizing_image($data);
 
 // Large (max 500px by 500px)
 $new_image_path = $new_path.'l_'.$product_id.'.'.$ext; // building the new targeted file path including new filename ("";)
 $data = array('old_image_path'=>$old_image_path, 'new_image_path'=>$new_image_path, 'width'=>500, 'height'=>500);
 $this->resizing_image($data);
 
 // For Copying Original Image.
 $new_image_path = $new_path.'orig_'.$product_id.'.'.$ext; // building the new targeted file path including new filename ("";)
 $data = array('old_image_path'=>$old_image_path, 'new_image_path'=>$new_image_path, 'copy_original'=>true);
 $this->resizing_image($data);
 
 echo 'All sizes: 
- t_'.$product_id.'.'.$ext.' = Thumbnail (max 40px by 40px); 
- s_'.$product_id.'.'.$ext.' = Standard (max 310px by 235px); 
     
- l_'.$product_id.'.'.$ext.' = Large (max 500px by 500px); and 
- orig_'.$product_id.'.'.$ext.' = Copying Original Image, 
 are copied into '.PATH_RESIZED_PRODUCT_IMAGE.' path.';
 die;
 
}

Call the above function to create different sizes image;
// Call the above function to create different sizes image;
$product_id = 18;
$old_image_path= 'http://ecx.images-amazon.com/images/I/81RXp-hIaNL._AA1500_.jpg';
resize_image($product_id, $old_image_path);

Thursday 19 July 2012

Validation of URL (Website Address) and Email using PHP

//Validation of URL (Website Address) and Email using PHP
$post = $_POST;

// Validation of URL or Website Address
if (!isset($post['api_user']) || empty($post['api_user']))
 $errors[] = 'Enter Website name';  
else if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $post['website']))
 $errors[] = ''.$post['website'].' website name is not valid.';

//Validation of Email Address
if (!isset($post['paypal_address']) || empty($post['paypal_address']))
 $errors[] = 'Enter valid Paypal Email Address.';
else if (!(filter_var($post['paypal_address'], FILTER_VALIDATE_EMAIL)))
 $errors[] = 'Enter valid PayPal email address.';

Monday 9 July 2012

Usage of preg_replace, search and replace {variable}


Regular Expression: Usage of preg_replace, search and replace {variable}, {variable_one} and join{string_var_able}.
$string = "This {variable} will be {variable_with_underscore}  and {variable}with will be replaced";
$pattern = array('/($|\{(\w+))\}/'); 
$replace = array('...'); 
$string = preg_replace($pattern, $replace, $string);

Tuesday 26 June 2012

Format Date Time using MySQL Query

// The Below Query will select all the users date in (20-06-2012 17:25:36) format while search the list of users records which are created (date_created) in the current month only.

SELECT DATE_FORMAT(date_created, '%d-%m-%Y %H:%i:%s') as initial_date
FROM users 
WHERE (SELECT MONTH(date_created)) = ( SELECT MONTH( NOW() ) ) 

Thursday 7 June 2012

Get the number of words from the string or paragraph

Get Chunk/No of words from the string or paragraphs 
This is similar to substr of the built-in php function.

// Fetch the chunk of string by number of words from the paragraph or string.
function substr_words ($string, $num_words)
{
 $string = explode (' ', $string);
 $string = array_slice ($string, 0, $num_words);
 return implode (' ', $string);
}

Wednesday 6 June 2012

Hours Mins and Seconds difference between two dates.

// Hours Mins and Seconds difference between two dates.
function timeDifference($date1=null, $date2=null)
{
 $date1 = !empty($date1) ? $date1 : date('Y-m-d H:i:s');
 $date2 = !empty($date2) ? $date2 : date('Y-m-d H:i:s');
 
 $dateDiff    = abs(strtotime($date1) - strtotime($date2));
 
    $fullHours   = floor($dateDiff / (60*60) );
    $fullMinutes = floor(($dateDiff-($fullHours*60*60))/60);   
    $fullSeconds = ($dateDiff-($fullHours*60*60)-($fullMinutes*60));
    
    return ('T-'.$fullHours.':'.$fullMinutes.':'.$fullSeconds);
}

To Run Yiic command for Yii Framework in Windows

// To Run Yiic command for Yii Framework in Windows 
Step-1: Go to the php directory where it is installed. e.g. C:\xampp\php
Step-2: Run below command.
             PATH1- Path to the framework folder: C:\xampp\htdocs\YiiMain\framework\yiic.php
             PATH2- Path to the new application folder: C:\xampp\htdocs\newApplicationName
C:\xampp\php>php PATH1 webapp PATH2


Friday 25 May 2012

Adding Days or Hours or Minutes or Seconds into date in MySQL (AddDate)

// The given query add a interval of 31 days to the '2012-04-15'.
ADDDATE('2012-04-15 16:30:30', INTERVAL 2 DAY); // Output: 2012-04-17 16:30:30
ADDDATE('2012-04-15 16:30:30', INTERVAL 3 HOUR); // Output: 2012-04-17 19:30:30
ADDDATE('2012-04-15 16:30:30', INTERVAL 45 MINUTE); // Output: 2012-04-17 17:15:30
ADDDATE('2012-04-15 16:30:30', INTERVAL 15 SECOND) // Output: 2012-04-17 16:30:45

//Sample MySQL Query
SELECT ADDDATE(date_user_created, INTERVAL 3 HOUR) as length_of_quote FROM users where user_id='23'



My Amazon Store

Wednesday 23 May 2012

Find the timestamp difference/two date difference in terms of day, hour, minute, second format using MySQL query

--
Find the timestamp difference/two date difference in terms of day, hour, minute, second format in MySQL query.
// MySQL convert timediff output to day, hour, minute, second format
SELECT 
CONCAT(TIMESTAMPDIFF(day,u.date_created, NOW()), 'Days ', 
 MOD( TIMESTAMPDIFF(hour,u.date_created, NOW()), 24), 'Hrs ',
 MOD( TIMESTAMPDIFF(minute,u.date_created, NOW()), 60), 'Mins ',
 MOD( TIMESTAMPDIFF(second,u.date_created, NOW()), 60), 'Secs ') as days_ago

/* OUTPUT */
1 day 23 hr 10 min 12 sec 

--

Wednesday 16 May 2012

Creating Cron-Jobs in CodeIgniter (CI) using CLI - CodeIgniter on the Command Line

To make a Cron Job work in CodeIgniter, you basically need to follow three steps;
  • Create a Model class
  • Create a Cron_Jobs Class
  • Set the Cron-Jobs command in the webserver.
Please, use the below example for the reference.
Step - 1: Create a Model Class.
class Warning_model extends CI_Model {
class Warning_model extends CI_Model {
	public function __construct()
	{
		parent::__construct();
	}
	
	public function addReferenceVATRecord()
	{
		//print_r($_SERVER);die;
		$data = array(	'valid_from' => date('Y-m-d H:i:s'),
						'type_id' => '1',
						'vat_rate' => '22.5',		
						'vat_calc' => '0.27',
						'updated' => date('Y-m-d H:i:s'),
						'updated_by' => '1'
					);
					
		$this->db->insert('reference_vat', $data);
		
		return $this->db->insert_id();
	}
}
/* End of file warning_model.php. */
/* Location: ./application/model/warning_model.php. */
Step - 2: Create a Cron_Jobs Controller Class.
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Cron_Jobs extends CI_Controller {
	
	public function __construct()
	{
		parent::__construct();
		
		$this->load->model('Warning_model', 'm_warning');

		// Call the cron job in below format: 
		// # /usr/local/bin/php /home/admin/admincentre.trunk.rc/index.php cron_jobs cron_add_vat_record 
	}

	public function cron_update_taxes($action='Cron Jobs')
	{
		echo "Hello {$action}".PHP_EOL;
	}
	
	public function cron_add_vat_record()
	{
		if ( $this->input->is_cli_request() )
		{
			// echo 'Request From CLI';
			$id = $this->m_warning->addReferenceVATRecord();
			echo $id.' '.PHP_EOL; die;
		}
		else { 
			echo 'Sorry Guys, we are bit smart this time.'; die;
		}
		
		//echo $id.' '.PHP_EOL; die;
	}
}
/* End of file cron_jobs.php. */
/* Location: ./application/controller/cron_jobs.php. */
Step - 3: Set the Cron-Jobs command in the webserver.
// Use the Croj Job command in below format: 
# /usr/local/bin/php /home/admin/admincentre.trunk.rc/index.php cron_jobs cron_add_vat_record 

Friday 11 May 2012

Solution to the problem defining the multiple databases on CodeIgnieter

// Solution to the problem defining the multiple databases on config/database.php on CodeIgnieter
/** Defining Database 1 */
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'dbusername_1';
$db['default']['password'] = 'dbpassword_1';
$db['default']['database'] = 'database_1';
$db['default']['dbdriver'] = 'mysql';
/* ----------
------- */
$db['default']['stricton'] = FALSE;

/** Defining Database 2 */
$db['manage']['hostname'] = 'localhost';
$db['manage']['username'] = 'dbusername_2';
$db['manage']['password'] = 'dbpassword_2';
$db['manage']['database'] = "database_2";
$db['manage']['dbdriver'] = "mysql";
/* ----------
------- */
$db['default']['stricton'] = FALSE;

/** Defining Database 3 */
$db['admin']['hostname'] = "localhost";
$db['admin']['username'] = "dbusername_3";
$db['admin']['password'] = "dbpassword_3";
$db['admin']['database'] = "database_3";
$db['admin']['dbdriver'] = "mysql";
/* ----------
------- */
$db['default']['stricton'] = FALSE;


PS: Please note that, all the databases username/password needs to be unique, if
they have shared the same username/password, then, there may be problem.
Actually, when I tried to use the same username/password for different databases,
I have found that the CodeIgniter is overriding my databases and I have solved it
by assigning unique username/password to each database.

Well, I am not sure, whether its CodeIgniter drawback or not. And, I thought it
would be helpful to share with you as well.

Cheers!

Monday 26 March 2012

Join Multiple Tables from Multiple Databases in PHP & in Codeigniter


// Join Multiple Tables from Multiple Databases in PHP
PS: You just you use the default database connection to execute the query or you can used either of any database connection if you have already made any other database connection instance. 

// This is for default database connection.
$sqlStr = "SELECT d1t1.id, t1.name, d2t2.no_of_sales, d3t2.customer_type
    FROM db1.Table1 as d1t1, db2.Table1 as d2t1, db3.Table2 as d3t2 
    WHERE d1t1.id='3' AND d3t2.customer_type='sales'";
$result = mysql_query($sqlStr);  
while($row = mysql_fetch_array($result))  {
  echo $id  = $row['id'];
        echo '\n';
        echo $name  = $row['name'];
        ..........
}
In the case of CodeIgniter, please find code below to pull the data from two or multiple database tables.


PS: You just you use the default ($this->db) database connection to execute the query or you can used either of any database connection if you have already made any other database connection instance.

// This is for default database connection.
$this->sqlStr= "SELECT d1t1.id, t1.name, d2t2.no_of_sales, d3t2.customer_type
                   FROM db1.Table1 as d1t1, db2.Table1 as d2t1, db3.Table2 as d3t2
     WHERE d1t1.id='3' AND d3t2.customer_type='sales'";
$query = $this->db->query($this->sqlStr);
$result = $query->row_array(); 
print_r($result);

Wednesday 21 March 2012

Create Multiple Databases Connections in Codeigniter


// To connect to Multiple Databases Connection in Codeigniter
// Open config/database.php and build the db connection array.

// This is for default database.
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'db_default';
........
.......

// This is for second database database.
$db['db2']['hostname'] = 'localhost';
$db['db2']['username'] = 'root';
$db['db2']['password'] = '';
$db['db2']['database'] = 'database2';
........
.......
Now, open your model files and create the db instance as per needs for second database.

class Rc_model extends CI_Model {
 private $db2; 
 public function Rc_model()
 {
  parent::__construct();
  // $this->db; // this is for default database connection.
  // $this->db = $this->load->database(); // this is also for default connection if you need a db instance.
  // Creating the db object for Second Database whose connection is available globally.
  $this->db2 = $this->load->database('db2', TRUE);
  $this->db2 =& $this->db2;
 }

 public function GetAllCategories()
 {
  $query = $this->db2->get_where('categories_table', array('active'=>'1'));
  return $query->result();
 }
}

Friday 16 March 2012

Get Random Float Value From Two Float Numbers

Calculate the random value between two float numbers.

/**
 * Calculate the random value between two float numbers. 
 * @param float $min Minimum float range value
 * @param float $max Maximum float range value
 * @return float Random Float value
 */
public function random_float ( $min, $max ) {
     return ( $min + lcg_value() * ( abs ( $max - $min ) ) );
}

Thursday 15 March 2012

Finds whether the type of a variable is true Float or not

The final version of function to check the actual float value and return boolean(true/false).

public function isTrueFloat($val) 
{
    if(is_string($val)) $val = trim($val);
    if( is_numeric($val) && ( is_float($val) || ( (float) $val > (int) $val
       || strlen($val) != strlen( (int) $val) ) && (ceil($val)) != 0 ))
    { 
       return true; 
    }
    else return false;
}

The following are the test results from the above function.
//Tests
'4.0'       returns true
'2.1'       returns true
0           returns false
"0"         returns false
3.          returns true
13          returns false
"12"        returns false
3.53        returns true
// Additional Tested ones
"0.27"      returns true
0.24        returns true

Wednesday 14 March 2012

Remove Inline NULL values from PHP arrays

Remove NULL values from PHP arrays with 1 line (Inline)
I had an array with something like the following: Array ( [0] => [1] => test [2] => fun ). But I don’t want [0], the empty value in the array.
After searching the web for a good solution, I saw that people were using anywhere from 4 to 10+ lines of code to remove null values from arrays. This is obviously overkill so I decided to tackle the problem myself.
Remove NULL values only
1
$new_array_without_nulls = array_filter($array_with_nulls, 'strlen');
Remove any FALSE values
This includes NULL values, EMPTY arrays, etc. Thanks to Paul Scott for pointing out this method.
1
$new_array_without_nulls = array_filter($array_with_nulls);