Friday, October 10, 2014

MySQL Sintax To Find Unmatched Records Between Two Table


Find difference record between two tables. Here the code:
SELECT username
FROM (
SELECT username FROM member_option
UNION ALL
SELECT username FROM member WHERE status='1'
) tbl
GROUP BY username
HAVING count(*) = 1
ORDER BY username;
Good Luck !!!

MySQL Sintax to Find Duplicate Entries


Here the code:
SELECT column FROM table_name group by column having count(*) >= 2
Good Luck !!!

Thursday, August 21, 2014

Adding foreign key in MySQL


This sql sintax can create link betwen key in some tables. Please used in InnoDB only. Here the code:

ALTER TABLE child_table_name
ADD FOREIGN KEY (P_ID)
REFERENCES parent_table_name (P_ID)

#example:
ALTER TABLE member_detail
ADD FOREIGN KEY (username)
REFERENCES member (username)

#foreign key will be deleted/updated if primary key deleted/updated
ON DELETE CASCADE ON UPDATE CASCADE

#parent will not be deleted if any child row exist
ON DELETE RESTRICT

#The script will be:
ALTER TABLE member_detail
ADD FOREIGN KEY (username)
REFERENCES member (username)
ON DELETE CASCADE ON UPDATE CASCADE

#Delete exist foreign key
ALTER TABLE member_detail DROP FOREIGN KEY member_detail_ibfk_1;

Good Luck !!!

Wednesday, March 26, 2014

Command Linux To Chmod File Only Or Directory Only Recursively In All Subdirectory

This command can chmod file only or directory only recursively. Here the code:
sudo su

#this command to chmod file only recursively
find . -type f -exec chmod 644 {} \;

#this command to chmod directory only recursively
find . -type d -exec chmod 755 {} \;
Good Luck !!!

Monday, March 24, 2014

PHP Code To Convert DateTime To Your Prefer Timezone

This function can convert DateTime to your prefer timezone. Here the code:
function convertTimezone($date,$zone){
$dates   = explode(" ", $date);
$tgl     = explode("-",$dates[0]);
$time    = explode(":",$dates[1]);

$newtime = mktime($time[0]+$zone,$time[1],$time[2],$tgl[1],$tgl[2],$tgl[0]); // H,i,s,m,d,Y
$newdate = date('Y-m-d H:i:s',$newtime);

return $newdate;
}

$date = "2014-03-30 06:01:09";
$newDate = convertTimezone($date,"+7");
echo $newDate;

Good Luck !!!

PHP Code To Make A Random Password

This function can generate a random password, use alphanumeric character, and eliminating the ambiguous character. Here the code:
function randomPassword(){
$digit = 8;
$karakter = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";

srand((double)microtime()*1000000);
$i = 0;
$pass = "";
while ($i <= $digit-1)
{
$num = rand() % 32;
$tmp = substr($karakter,$num,1);
$pass = $pass.$tmp;
$i++;
}
return $pass;
}

$password = randomPassword()
echo $password;
Good Luck !!!

PHP Code To Limiting Words Number In PHP

This function can limiting words number. Usually this used to limit name of person. Here the code:
function word($word,$limit){
$result='';
$words=@explode(" ",$word);
for($i=0;$i<=$limit-1;$i++){
$result.=@$words[$i]." ";
}
return $result;
}

$name = "iben arief bin padi";

echo word($name,1); // output: iben
echo word($name,2); // output: iben arief
echo word($name,3); // output: iben arief bin
echo word($name,4); // output: iben arief bin padi
Good Luck !!!

PHP Code To Auto Detect URL in Text Then Make Clickable


This function can auto detect URL in  all text, then make the URL clickable. Here the code:
function autolink( &$text, $target='_blank', $nofollow=true )
{
  // grab anything that looks like a URL...
  $urls  =  _autolink_find_URLS( $text );
  if( !empty($urls) ) // i.e. there were some URLS found in the text
  {
    array_walk( $urls, '_autolink_create_html_tags', array('target'=>$target, 'nofollow'=>$nofollow) );
    $text  =  strtr( $text, $urls );
  }
}

function _autolink_find_URLS( $text )
{
  // build the patterns
  $scheme         =       '(http:\/\/|https:\/\/)';
  $www            =       'www\.';
  $ip             =       '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
  $subdomain      =       '[-a-z0-9_]+\.';
  $name           =       '[a-z][-a-z0-9]+\.';
  $tld            =       '[a-z]+(\.[a-z]{2,2})?';
  $the_rest       =       '\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1}';            
  $pattern        =       "$scheme?(?(1)($ip|($subdomain)?$name$tld)|($www$name$tld))$the_rest";
    
  $pattern        =       '/'.$pattern.'/is';
  $c              =       preg_match_all( $pattern, $text, $m );
  unset( $text, $scheme, $www, $ip, $subdomain, $name, $tld, $the_rest, $pattern );
  if( $c )
  {
    return( array_flip($m[0]) );
  }
  return( array() );
}

function _autolink_create_html_tags( &$value, $key, $other=null )
{
  $target = $nofollow = null;

  if(stripos($key, "http")===FALSE){ $key="http://".$key;}

  if( is_array($other) )
  {
    $target      =  ( $other['target']   ? " target=\"$other[target]\"" : null );
    $nofollow    =  ( $other['nofollow'] ? ' rel="nofollow"'            : null );     
  }
  $value = "<a title=\"Modify your prefer title\" href=\"$key\"$target$nofollow>$key</a>";


$text = "this is a link to http://www.google.com/";
autolink($text);
echo $text;
Good Luck !!!

PHP Code To Send Email With Swiftmailer Library

Before use this function, please download swiftmailer library from this source http://swiftmailer.org/download. This function can send email using PHP with Swiftmailer Library. Place This file in same path with folder 'lib/'. This function is automatic detect body of message in plain text or html. Here the code:
function sendEmail($method,$subject,$from,$to,$body){
require_once dirname(__FILE__).'/lib/swift_required.php';
if($method=="smtp"){
$smtp     = "smtpaddress"; // ex: smtp.mandrillapp.com
$port     = 587; // ex: 587
$username = "yourusername"; // ex: blabla@gmail.com
$password = "yourpassword"; // ex: passwordtoaccess
$transport = Swift_SmtpTransport::newInstance($smtp, $port)
   ->setUsername($username)
   ->setPassword($password);
}
else if($method=="sendmail"){
   $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
}
else if($method=="mail"){
   $transport = Swift_MailTransport::newInstance();
}
else{
   $transport = Swift_MailTransport::newInstance();
}
// auto detect plain text or html
if($body != strip_tags($body)){$text="text/html";}
else{$text="text/plain";}

$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance($subject)
   ->setFrom($from)
   ->setTo($to)
   ->setBody($body,$text);

$result = $mailer->send($message);
return $result;
}

// sample send email using smtp method
$method  = "smtp";
$subject = "It's cool";
$from    = array("youremail@blabla.com" => "iben");
$to      = array("yourdestination@blabla.com" => "my dear");
$body    = "<b>It's great script made by iben</b>";
$send    = sendEmail($method,$subject,$from,$to,$body);

echo $send; // output: true or false

// To send with other method just change $method to your prefer (sendmail, mail, or smtp)

Good Luck !!!

PHP Code To Calculate The Difference Between Two Dates

This function can calculate the difference between two dates. Here the code:
function diff($firstDate,$secondDate){
   $first=explode("-",$firstDate);
   $second=explode("-",$secondDate);
   $first = @GregorianToJD($first[1], $first[2], $first[0]);
   $second = @GregorianToJD($second[1], $second[2], $second[0]);
   $diff = $second - $first;
return $diff;
}

echo diff("2014-02-25","2014-02-28"); // output is 3
Good Luck !!!

PHP Code To Resize and Crop Image

This function resize image and crop image. Here the Code:
// Function to resize image
function resizeImage($image,$width,$height,$scale) {
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
$source = imagecreatefromjpeg($image);
imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
imagejpeg($newImage,$image,90);
chmod($image, 0777);
return $image;
}

// Function to crop image
function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale){
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
$source = imagecreatefromjpeg($image);
imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,$newImageHeight,$width,$height);
imagejpeg($newImage,$thumb_image_name,90);
chmod($thumb_image_name, 0777);
return $thumb_image_name;
}

// Function to get image height
function getHeight($image) {
$sizes = getimagesize($image);
$height = $sizes[1];
return $height;
}

// Function to get image width
function getWidth($image) {
$sizes = getimagesize($image);
$width = $sizes[0];
return $width;
}

// Start to resize image
$large_image_location = "images/imagename.jpg"; // path to image
chmod($large_image_location, 0777);
$width = getWidth($large_image_location);
$height = getHeight($large_image_location);
$max_width = "300"; // maximum image width, write your prefered
if ($width > $max_width){
$scale = $max_width/$width;
$uploaded = resizeImage($large_image_location,$width,$height,$scale);
}
else{
$scale = 1;
$uploaded = resizeImage($large_image_location,$width,$height,$scale);
}

// Start to crop image
if (($height > $width) and ($width > 300)){
$x1 = 0;$y1 = 0;
$x2 = 300;$y2 = 250;
$w = 300;$h = 250;
$scale = 300/$w;
$cropped = resizeThumbnailImage($large_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
}
else if (($height > $width) and ($width < 300) and ($height > 250)){
$x1 = 0;$y1 = 0;
$x2 = $width;$y2 = 250;
$w = $width;$h = 250;
$scale = $width/$w;
$cropped = resizeThumbnailImage($large_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
}
else if (($height > $width) and ($width < 300) and ($height < 250)){
$x1 = 0;$y1 = 0;
$x2 = $width;$y2 = $height;
$w = $width;$h = $height;
$scale = $width/$w;
$cropped = resizeThumbnailImage($large_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);

}
Good Luck !!!

Sunday, March 23, 2014

PHP Code To Validate Email Address and Domain


This function can Validate Email Address and Domain. Here the Code:
$email = "test test@yahoo.com"; // Invalid Formating
//$email = "testtest@yahoo.comx"; // Invalid Domain
//$email = "testtest@yahoo.com"; // Valid Email

// validate address formating
if (filter_var($email, FILTER_VALIDATE_EMAIL) != FALSE) {
    echo "Valid email address formatting!\n";
}else{
    echo "Invalid formatting\n";
}

// validate domain of email
$domain = substr($email, strpos($email, '@') + 1);
if  (checkdnsrr($domain) !== FALSE) {
    echo "Domain is valid!\n";
}else{
    echo "Domain is not valid!\n";
}
Good Luck !!!

PHP code to make Indonesia Rupiah Format


Simple Indonesia Rupiah Format in PHP. Here The Code:
function rupiah($a){
if(stripos($a, ".")===FALSE){$a = $a.".00";}

$pecah    = explode(".", $a);
$depan    = strrev($pecah[0]);
$belakang = $pecah[1];
$jum      = strlen($depan);
$res      = "";

for($i=0;$i<=$jum-1;$i++){
if($i%3==0 and $i!=0){$res.=".".$depan[$i];}
else{$res.=$depan[$i];}
}
return "Rp ".strrev($res).",".$belakang;
}

$a = "2090705.57";

echo rupiah($a);

Good Luck !!!

PHP Code To Find All Directory Or File Recursively

This function can find all directory or file in a path. Here the Code:
function glob_recursive($pattern, $flags = 0){
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir){
$files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
}
return $files;
}

$results = glob_recursive("*", $flags = 0);
foreach ($results as $result) {
$type = is_file($result) ? "File" : "Dir";
echo $result."\n".$type."\n\n";
}
Good Luck !!!