Tuesday, December 6, 2016

Piechart using Highchart and MySQL Database!


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Piechart using Highchart and MySQL Database Showing turnover of Different channel over a given period of time.

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////






/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// CODE
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////

//// index.php

///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
include("db.php");
$obj=new DB;
$sql="select * from pakchanel";
//$obj->hc($sql);
$ch="NEO";
$x=$obj->hc($sql,$ch);
//print_r($x);
$results=$obj->getSqlTable($sql);
//echo'<pre>';print_r($results);
/*[["ABC",450000],["BBC",650000],["NDTV",120000],["ZEE",230000],["STAR PLUS",630000],["SONY",260000],["TIMES NOW",870000],["ZOOM",850000],["COLORS",190000],["QUBO",985600],["EI",670098],["NBC10",760657],["WHY",8100900]]*/
?>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="selchanel" align="left">

<select id="selchannel" onchange="selchannel(this.value)">
<?php foreach($results as $result){ ?>
<option value="<?php echo $result['name']?>"><?php echo $result['name']?></option>
<?php }?>
</select>

<select id="selduration" onchange="selduration(this.value)">
<option value="thisweek">This week</option>
<option value="thismonth">This month</option>
<option value="thisyear">This year</option>
<option value="last3month">Last 3 month</option>
<option value="last6month">Last 6 month</option>
<option value="all">All</option>
</select>
</div>
<div id="display">
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>


<script>
var p=<?php echo json_encode($x, JSON_NUMERIC_CHECK);?>;
$(function () {
    $('#container').highcharts({
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
        },
        title: {
            text: 'Pakistani Channel Perforance Report'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                    }
                }
            }
        },
        series: [{
            name: "Brands",
            colorByPoint: true,
         
data: p
        }]//SERIES END
    });
});
</script>
</div>
<script>
/////functions
function selchannel(x){
//alert(x);
$.ajax({
   type:"POST",
   url:"update.php",
   data:{"channel":x},
   success:function(data){
   $("#display").html(data);
   }
 

});
}


function selduration(betdate){
$.ajax({
   type:"POST",
   url:"betdate.php",
   data:{"betdate":betdate},
   success:function(data){
   $("#display").html(data);
   }
 

});
}
</script>

///////////////////////////////////////////////////////////////////////////////////////////////////

//// End index.php

///////////////////////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////////////////////

//// db.php

///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
///////////////////////////////////////////////////////////////////////////////////////////////////
//// Muna Database Function Library
///////////////////////////////////////////////////////////////////////////////////////////////////
//// Database Functions
///////////////////////////////////////////////////////////////////////////////////////////////////
////
//// Usage:
//// $db = new DB(); //instantiate using default read-only connection
//// $db = new DB($user,$pass); //instantiate using a specific login/pass
////
///////////////////////////////////////////////////////////////////////////////////////////////////

$showsql = true;
//$db = new DB();

class DB {
  private $dbhost = "localhost";
  private $dbuser = "root";
  private $dbpass = "";
  private $dbname = "chart";

  public $error = "";

  function __construct()
    {
    }
  public function getSqlTable($sql){
    $resarr=array();
     $con = mysql_connect($this->dbhost,$this->dbuser,$this->dbpass);
if (!$con) {
die("Could not connect to database!");
}
mysql_select_db($this->dbname, $con);
//mysql_select_db("esigns_prod", $con);
$result = mysql_query($sql, $con);
//true,selected: true
while($res=mysql_fetch_assoc($result)){
$resarr[]=$res;
}

mysql_close($con);

return $resarr;
         //list = array('id' => $fid, 'name' => $fname);
}
  public function hc($sql,$ch){
    $resarr=array();
$rows=array();
     $con = mysql_connect($this->dbhost,$this->dbuser,$this->dbpass);
if (!$con) {
die("Could not connect to database!");
}
mysql_select_db($this->dbname, $con);
//mysql_select_db("esigns_prod", $con);
$result = mysql_query($sql, $con);
//true,selected: true
while($res=mysql_fetch_assoc($result)){
if($res['name']==$ch){
 $resarr[]=array('name'=>$res['name'],'y'=>$res['amount'],'sliced'=>"true",'selected'=>"true");
 }

else{
 $resarr[]=array('name'=>$res['name'],'y'=>$res['amount']);
}
}

mysql_close($con);
//return $rows;
$res=json_encode($resarr, JSON_NUMERIC_CHECK);
return $resarr;
         //list = array('id' => $fid, 'name' => $fname);
}

//---------------
//foreach ($customers as $customer) {
//    $row[0]=$customer->cust_name;
//    $row[1]=$customer->monthly_income;
//    array_push($rows,$row);
//}
//print json_encode($rows, JSON_NUMERIC_CHECK);
//---------------
public function ReportError ($sql, $message) {
//echo "SQL ERROR:\nMessage: $message\nSQL: $sql\n";
$this->error = $message;
}





//highchart
public function GetChart ($sql)
    {
    $output = Array();
    $con = $this->GetDB();
    if (!$con) {return -1;}
    $result = mysql_query($sql, $con);
    if ($result == 0) {return 0;}
$rows = Array();
    while ($res = mysql_fetch_object($result)) //will ignore anything that comes after
{
    $row[0]=$res->year;
             $row[1]=$res->amount;
//$row[1]=$channel->Date;
             array_push($rows,$row); //array_push(array,value1,value2...)

}
    mysql_close($con);
//print_r($rows);
    print_r(json_encode($rows, JSON_NUMERIC_CHECK));
    }
//delete by muna

public function deleteRow($sql) {
$con = mysql_connect($this->dbhost,$this->dbuser,$this->dbpass);
if (!$con) {
die("Could not connect to database!");
}
mysql_select_db($this->dbname, $con);
//mysql_select_db("esigns_prod", $con);
$result = mysql_query($sql, $con);
mysql_close($con);
return $result;
}


//returns a 1d list of results (using the first column returned)
public function GetList2 ($sql) {
$con = mysql_connect($this->dbhost,$this->dbuser,$this->dbpass);
if (!$con) {
die("Could not connect to database!");
}
//mysql_select_db("esigns_prod", $con);
$result = mysql_query($sql, $con);
while ($row = mysql_fetch_array($result)) {
$results[] = $row[0];
}
mysql_close($con);
return $results;
}



public function GetRow2 ($sql) {
$con = mysql_connect($this->dbhost,$this->dbuser,$this->dbpass);
if (!$con) {
die("Could not connect to database!");
}
//mysql_select_db($this->dbname, $con);
mysql_select_db("esigns_prod", $con);
$result = mysql_query($sql, $con);
//echo $sql;
//var_dump($result);
//echo mysql_error($con);
//mysql_close($con);
return mysql_fetch_assoc($result);
}


  public function GetDB ()
    {
    $con = mysql_connect($this->dbhost,$this->dbuser,$this->dbpass);
    if (!$con)
          {
          die("Could not connect to database!");
          }
    mysql_select_db($this->dbname, $con);
    return $con;
    }


  public function Clean($sql)
         {
         return mysql_real_escape_string($sql, $this->GetDB());
         }


  public function Query ($sql)
    {
    $output=0;
    $con = $this->GetDB();
    if (!$con) {return -1;}
    $result = mysql_query($sql, $con);
    if (!isset($result))
          {
          return 0;
          }
    if (!$result) {return 0;}
    if ($row = mysql_fetch_row($result))
      {
        $output = $row[0];
      }
    mysql_close($con);
    return $output;
    }

  //returns the first two columns in an sql query as a keyed array
  public function GetArray ($sql)
        {
    $output = Array();
    $con = $this->GetDB();
    if (!$con) {return -1;}
    $result = mysql_query($sql, $con);
    if ($result == 0) {return 0;}
    while ($row = mysql_fetch_row($result))
      {
                //verify there are two rows of data, otherwise return an indexed list of the first
            $output[$row[0]] = $row[1];
      }
    mysql_close($con);
    return $output;
        }
  //returns the first column of each row returned
  public function GetList ($sql)
        {
    $output = Array();
    $con = $this->GetDB();
    if (!$con) {return -1;}
    $result = mysql_query($sql, $con);
    if ($result == 0) {return 0;}
    while ($row = mysql_fetch_row($result))
      {
            array_push($output, $row[0]);
      }
    mysql_close($con);
    return $output;
        }


  public function GetResult ($sql)
    {
    $con = $this->GetDB();
    if (!$con) {return 0;}
    $result = mysql_query($sql, $con);
    //mysql_close($con);
    return $result;
    }


public function GetJSON ($sql)
    {
    $output = Array();
    $con = $this->GetDB();
    if (!$con) {return -1;}
    $result = mysql_query($sql, $con);
    if ($result == 0) {return 0;}
    while ($row = mysql_fetch_row($result)) //will ignore anything that comes after
{
$data = Array();
for ($i=0; $i<mysql_num_fields($result);  $i++) {
$data[mysql_fetch_field($result, $i)->name] = $row[$i];
}
array_push($output, $data);
}
    mysql_close($con);
    return json_encode($output);
    }

public function GetTable ($sql)
    {
    $output = Array();
    $con = $this->GetDB();
    if (!$con) {return -1;}
    $result = mysql_query($sql, $con);
    if ($result == 0) {return 0;}
    while ($row = mysql_fetch_row($result)) //will ignore anything that comes after
{
$data = Array();
for ($i=0; $i<mysql_num_fields($result);  $i++) {
$data[mysql_fetch_field($result, $i)->name] = $row[$i];
}
array_push($output, $data);
}
    mysql_close($con);
    return $output;
    }

public function InsertSql ($sql)
    {
    $output = Array();
    $con = $this->GetDB();
    if (!$con) {return -1;}
    $result = mysql_query($sql, $con);
    if ($result) {$output= 1;}
else $output= 0;
 
    mysql_close($con);
    return $output;
    }






  public function GetRow ($sql)
    {
    $output = Array();
    $con = $this->GetDB();
    if (!$con) {return -1;}
    $result = mysql_query($sql, $con);
    if ($result == 0) {return 0;}
    if ($row = mysql_fetch_row($result)) //will ignore anything that comes after
      {
                $output = $row;
      }
    mysql_close($con);
    return $output;
    }

  public function GetRowObject ($sql)
    {
    $output = Array();
    $con = $this->GetDB();
    if (!$con) {return -1;}
    $result = mysql_query($sql, $con);
    if ($result == 0) {return 0;}
    if ($row = mysql_fetch_assoc($result)) //will ignore anything that comes after
      {
                $output = $row;
      }
    mysql_close($con);
    return $output;
    }


  public function GetRows ($sql)
    {
    $output = Array();
    $con = $this->GetDB();
    if (!$con) {return -1;}
    $result = mysql_query($sql, $con);
    if ($result == 0) {return 0;}
    while ($row = mysql_fetch_row($result)) //will ignore anything that comes after
      {
array_push($output, $row);
      }
    mysql_close($con);
    return $output;
    }


  public function Command ($sql)
    {
global $showsql;
$this->error = "";
//if ($showsql) {echo "SQL: $sql\n";}
    $con = $this->GetDB();
    if (!$con) {return 0;}
    $result = mysql_query($sql, $con);
    $rows = mysql_affected_rows($con);
        if ($rows < 1)
          {
 $this->error = mysql_error($con);
 //$this->ReportError($sql, mysql_error($con));
          //echo "DB ERROR: " . mysql_error($con) . "\n";
          }
    mysql_close($con);
    return $rows;
    }





}
?>

///////////////////////////////////////////////////////////////////////////////////////////////////

//// End db.php

///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////

//// betdate.php

///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
include("db.php");
session_start();
$obj=new DB;
$sql="select * from pakchanel";
//$obj->hc($sql);
$betdate=$_REQUEST['betdate'];

$sql="";
switch($betdate){
   case "thisweek":
   $dtst=date("Y-m-d", strtotime('this week', time()) ); //20150130 AND
   $dtend=date("Y-m-d", strtotime("today") );//20151005 //sae in all case
   $sql.="SELECT * FROM  pakchanel where DATE(Date) BETWEEN str_to_date('".$dtst."','%Y-%m-%d') AND str_to_date('".$dtend."','%Y-%m-%d')";
   break;
 
   case "thismonth":
   $dtst=date("Y-m-d", strtotime(date('01-m-Y')) );
   $dtend=date("Y-m-d", strtotime("today") );//20151005
   $sql.="SELECT * FROM  pakchanel where DATE(Date) BETWEEN str_to_date('".$dtst."','%Y-%m-%d') AND str_to_date('".$dtend."','%Y-%m-%d')";
   break;
 
   case "thisyear":
   $dtst=date("Y-m-d", strtotime(date('01-01-Y')) );
   $dtend=date("Y-m-d", strtotime("today") );//20151005
   $sql.="SELECT * FROM  pakchanel where DATE(Date) BETWEEN str_to_date('".$dtst."','%Y-%m-%d') AND str_to_date('".$dtend."','%Y-%m-%d')";
   break;
 
   case "last3month":
   $dtst=date("Y-m-d", strtotime('- 3 month') );
   $dtend=date("Y-m-d", strtotime("today") );//20151005
   $sql.="SELECT * FROM  pakchanel where DATE(Date) BETWEEN str_to_date('".$dtst."','%Y-%m-%d') AND str_to_date('".$dtend."','%Y-%m-%d')";
   break;
 
   case "last6month":
   $dtst=date("Y-m-d", strtotime('- 6 month') );
   $dtend=date("Y-m-d", strtotime("today") );//20151005
   $sql.="SELECT * FROM  pakchanel where DATE(Date) BETWEEN str_to_date('".$dtst."','%Y-%m-%d') AND str_to_date('".$dtend."','%Y-%m-%d')";
   break;
 
   case "all":
   $sql.="SELECT * FROM  pakchanel";
   break;

}
if(isset($_SESSION['channel'])){
echo $ch=$_SESSION['channel'];
}
else
{echo $ch="PTV";}
$x=$obj->hc($sql,$ch);
?>


<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>


<script>
var p=<?php echo json_encode($x, JSON_NUMERIC_CHECK);?>;
$(function () {
    $('#container').highcharts({
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
        },
        title: {
            text: 'My 1st display of pie chart'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                    }
                }
            }
        },
        series: [{
            name: "Brands",
            colorByPoint: true,
         
data: p
        }]//SERIES END
    });
});
</script>

///////////////////////////////////////////////////////////////////////////////////////////////////

//// End betdate.php

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////

//// update.php

///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
session_start();
include("db.php");
$obj=new DB;
$sql="select * from pakchanel";
//$obj->hc($sql);
$ch=$_REQUEST['channel'];
$_SESSION['channel']=$ch;
$x=$obj->hc($sql,$ch);

?>


<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>


<script>
var p=<?php echo json_encode($x, JSON_NUMERIC_CHECK);?>;
$(function () {
    $('#container').highcharts({
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
        },
        title: {
            text: 'My 1st display of pie chart'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                    }
                }
            }
        },
        series: [{
            name: "Brands",
            colorByPoint: true,
         
data: p
        }]//SERIES END
    });
});
</script>

///////////////////////////////////////////////////////////////////////////////////////////////////

//// End update.php

///////////////////////////////////////////////////////////////////////////////////////////////////







UPS Tracking API using PHP to Track status of Shipment

///////////////////////////////////////////////////////////////////////////////////////////////////
//// index.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<div align="center">
<form action="#" method="post">
<table>
  <tr><td>Enter Tracking No</td><td><input type="text" id="trackno" name="trackno" /></td><td><input type="submit" value="Enter" id="sub" name="sub" /></td></tr>
</table>
</form>
</div>
<?php
include("track_detail.php");
if(isset($_REQUEST['sub'])){
 echo $trackingNumber=$_REQUEST['trackno'];
 $objTrack=new trackApi;
 $objTrack->trackingApi($trackingNumber);
}
?>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End index.php
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// track_detail.php
///////////////////////////////////////////////////////////////////////////////////////////////////

<?php
//beginin track Api

class trackApi{
 function trackingApi($trackingNumber){
  $ch=curl_init("https://www.ups.com/ups.app/xml/Track");
  curl_setopt($ch, CURLOPT_HEADER,1);
  curl_setopt($ch, CURLOPT_POST,1);
  curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch, CURLOPT_POSTFIELDS,
                    "xmlRequest=" .$this->getXml($trackingNumber));
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $res=curl_exec($ch);
  $data=strstr($res,'<?');
  $myres=simplexml_load_string($data);
  $myres->asXML("result.xml");
  header("Location:status.php");  

 }

 function getXml($trackingNumber){
 $data="<?xml version=\"1.0\"?>
        <AccessRequest xml:lang='en-US'>
                <AccessLicenseNumber>1C7D006816ADB170</AccessLicenseNumber>
                <UserId>YOUR_ID</UserId>
                <Password>YOUR_PWD</Password>
        </AccessRequest>
        <?xml version=\"1.0\"?>
        <TrackRequest>
                <Request>
<RequestOption>10</RequestOption>
                        <TransactionReference>
                                <CustomerContext>
                                        <InternalKey>KEY</InternalKey>
                                </CustomerContext>
                                <XpciVersion>1.0</XpciVersion>
                        </TransactionReference>
                        <RequestAction>Track</RequestAction>
                </Request>
        <TrackingNumber>$trackingNumber</TrackingNumber>
        </TrackRequest>";
return $data;
 }//////////////////end get XML

}/////////////END class
?>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End track_detail.php
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// status.php
///////////////////////////////////////////////////////////////////////////////////////////////////

<?php
$xml=simplexml_load_file("result.xml");
if($xml->Response->Error->ErrorCode){
echo "Status:".$xml->Response->ResponseStatusDescription."<br/>";
echo "Error Code:".$xml->Response->Error->ErrorCode."<br/>";
echo "Error Severity:".$xml->Response->Error->ErrorSeverity."<br/>";
echo "Error ErrorDescription:".$xml->Response->Error->ErrorDescription."<br/>";


}
else{

echo "Status:".$xml->Response->ResponseStatusDescription."<br/>";
echo "Date:".$xml->Shipment->Package->Activity->Date."<br/>";
echo "Left At:".$xml->Shipment->Package->Activity->ActivityLocation->Description."<br/>";
echo "Signed For By:".$xml->Shipment->Package->Activity->ActivityLocation->SignedForByName."<br/>";
$data=$xml->Shipment->Package->Activity->ActivityLocation->SignatureImage->GraphicImage;
echo'<img src="data:image/GIF;base64,'.$data.'">';
}
?>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End status.php
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// result.xml
///////////////////////////////////////////////////////////////////////////////////////////////////
<?xml version="1.0"?>
<TrackResponse><Response><TransactionReference><XpciVersion>1.0</XpciVersion></TransactionReference><ResponseStatusCode>1</ResponseStatusCode><ResponseStatusDescription>Success</ResponseStatusDescription></Response><Shipment><Shipper><ShipperNumber>7X987R</ShipperNumber><Address><AddressLine1>7729 LOCHLLN DR</AddressLine1><City>BRIGHTON</City><StateProvinceCode>MI</StateProvinceCode><PostalCode>48116   8329</PostalCode><CountryCode>US</CountryCode></Address></Shipper><ShipTo><Address><AddressLine1>11 HULSE RD</AddressLine1><City>SETAUKET</City><StateProvinceCode>NY</StateProvinceCode><PostalCode>117333617</PostalCode><CountryCode>US</CountryCode></Address></ShipTo><Service><Code>003</Code><Description>GROUND</Description></Service><ReferenceNumber><Code>01</Code><Value>ES230821</Value></ReferenceNumber><ShipmentIdentificationNumber>1Z7X887R0354471707</ShipmentIdentificationNumber><PickupDate>20141114</PickupDate><DeliveryDateUnavailable><Type>Scheduled Delivery</Type><Description>Scheduled Delivery Date is not currently available, please try back later</Description></DeliveryDateUnavailable><Package><TrackingNumber>1Z7X887R03754471707</TrackingNumber><Activity><ActivityLocation><Address><AddressLine1>11 HULSE RD</AddressLine1><City>EAST SETAUKET</City><StateProvinceCode>NY</StateProvinceCode><PostalCode>11733</PostalCode><CountryCode>US</CountryCode></Address><Code>AI</Code><Description>DOCK</Description><SignedForByName>AYERLE</SignedForByName><SignatureImage><GraphicImage>CxhwfZyH35h1HCXBaL28yiSEHsnEO8ow8RUAAAD.....</GraphicImage><ImageFormat><Code>GIF</Code><Description>Base 64 encoded gif</Description></ImageFormat></SignatureImage><PODLetter><HTMLImage>9EWT48L0hUTU...</HTMLImage></PODLetter></ActivityLocation><Status><StatusType><Code>D</Code><Description>DELIVERED</Description></StatusType><StatusCode><Code>KB</Code></StatusCode></Status><Date>20141118</Date><Time>115000</Time></Activity><PackageWeight><UnitOfMeasurement><Code>LBS</Code></UnitOfMeasurement><Weight>18.00</Weight></PackageWeight><ReferenceNumber><Code>01</Code><Value>FR30821</Value></ReferenceNumber></Package></Shipment></TrackResponse>

///////////////////////////////////////////////////////////////////////////////////////////////////
//// End result.xml
///////////////////////////////////////////////////////////////////////////////////////////////////


Saturday, December 3, 2016

Google Book API Searching By Name,Type,Title...Order

//index.php pge

<form action="result.php" method="post">
<table>
<tr><td>Enter The Book Name:<input type="text" name="srch" id="srch" /></td></tr>
<tr><td>Select The Type:
<select id="myfiter" name="myfiter"/>
<option value="ebooks">Ebooks</option>
<option value="paid-ebooks">Paid Ebooks</option>
<option value="free-ebooks">Free Ebooks</option>
<option value="full">Full View</option>
<option value="partial">Ebooks</option>
</select>
</td></tr>

<tr><td>Select The Print Type:
<select id="printType" name="printType"/>
<option value="all">All Type</option>
<option value="books">Books</option>
<option value="magazines">Magazines</option>
</select>
</td></tr>

<tr><td>Order By:
<select id="order" name="order"/>
<option value="relevance">Relevance</option>
<option value="newest">Newest</option>
</select>
</td></tr>

<tr><td>No Of Result:
<select id="limit" name="limit"/>
<?php
for($i=1; $i<=30; $i+=2){
 ?>
<option value="<?php echo $i;?>" <?php if($i==5){?>" selected="selected" <?php } ?>><?php echo $i; ?></option>
<?php } ?>
</select>
</td></tr>

<tr><td><input type="submit" name="sub" id="sub" /></td></tr>
</table>
</form>


//result.php page
<?php
//replace it with your own
$apikey ='Wamyyyjjjj00000mutguiopred90mmmopred'; 



if(isset($_REQUEST['srch'])){
$bookSearchTerm=$_REQUEST['srch'];
}
else{
$bookSearchTerm="Oscar Wilde";
}
$q = urlencode($bookSearchTerm);

if(isset($_REQUEST['myfiter'])){
$filter=$_REQUEST['myfiter'];
}
else{
$filter="free-ebooks";
}

if(isset($_REQUEST['printType'])){
$printType=$_REQUEST['printType'];
}
else{
$printType="books";
}

if(isset($_REQUEST['order'])){
$orderBy=$_REQUEST['order'];
}
else{
$orderBy="relevance";
}

if(isset($_REQUEST['limit'])){
$maxResults=$_REQUEST['limit'];
}
else{
$maxResults=5;
}
$url = 'https://www.googleapis.com/books/v1/volumes?q=' . $q . '&key=' . $apikey . '&filter=' . $filter.'&printType='.$printType.'&orderBy=' .$orderBy.'&maxResults=' . $maxResults;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
$body = curl_exec($ch);
curl_error($ch);
curl_close($ch);

// now, process the JSON string
$data = json_decode($body, true);

$num=count($data['items']);
  $cntr=1;
for($i=0; $i<$num; $i++){
   echo $cntr.")<br /> \n";
   $src=$data['items'][$i]['volumeInfo']['imageLinks']['smallThumbnail'];
   echo '<img src="'.$src.'" alt="error"> <br />';
   echo"<strong><font color=red>Title:</font></strong>" .$data['items'][$i]['volumeInfo']['title'], "<br />";
   echo "<strong><font color=red>Author:</font></strong>" .$data['items'][$i]['volumeInfo']['authors'][0], "<br />";
  
   if(isset($data['items'][$i]['volumeInfo']['publisher'])){
   echo "<strong><font color=red>Publisher:</font></strong>" .$data['items'][$i]['volumeInfo']['publisher'], "<br /> ";
   }
   echo "<strong><font color=red>Published Date:</font></strong>" .$data['items'][$i]['volumeInfo']['publishedDate'], "<br /> ";
    
   if(isset($data['items'][$i]['volumeInfo']['subtitle'])){
   echo "<strong><font color=red>Sub Title:</font></strong>" .$data['items'][$i]['volumeInfo']['subtitle'], "<br /> ";
   }
    if(isset($data['items'][$i]['volumeInfo']['pageCount'])){
   echo "<strong><font color=red>No of Page:</font></strong>" .$data['items'][$i]['volumeInfo']['pageCount'], "<br /> ";
   }
   echo "<strong><font color=red>Print Type:</font></strong>" .$data['items'][$i]['volumeInfo']['printType'], "<br /> ";
  
   if(isset($data['items'][$i]['volumeInfo']['categories'])){
   echo "<strong><font color=red>Categories:</font></strong>" .$data['items'][$i]['volumeInfo']['categories'][0], "<br /> ";
   }
   if($data['items'][$i]['volumeInfo']['language']=='en'){
   echo "<strong><font color=red>Language:</font></strong>","English", "<br /> ";
   }
   else{
   echo "<strong><font color=red>Language:</font></strong>" .$data['items'][$i]['volumeInfo']['language'], "<br /> ";
   }
    if(isset($data['items'][$i]['saleInfo']['buyLink'])){
  echo "<strong><font color=red>Buy Link:</font></strong> <a href=" .$data['items'][$i]['saleInfo']['buyLink'].">Buy-this-book</a> <br /> ";
}  
 
   if(isset($data['items'][$i]['saleInfo']['listPrice']['amount'])){
   echo "<strong><font color=red>List Price:</font></strong>" .$data['items'][$i]['saleInfo']['listPrice']['amount'].$data['items'][$i]['saleInfo']['listPrice']['currencyCode'], "<br /> ";
   }
   if($data['items'][$i]['saleInfo']['isEbook']==1){
   echo "<strong><font color=red>Is E-Book:</font> </strong>Yes<br /> ";
   }
  
  if(isset($data['items'][$i]['volumeInfo']['averageRating'])){
   echo "<strong><font color=red>Average Rating:</font></strong>" .$data['items'][$i]['volumeInfo']['averageRating'], "<br /> ";
   }
     if(isset($data['items'][$i]['volumeInfo']['ratingsCount'])){
   echo "<strong><font color=red>Ratings Count:</font></strong>" .$data['items'][$i]['volumeInfo']['ratingsCount'], "<br /> ";
   }
   echo "<strong><font color=red>Sale Info:</font></strong>" .$data['items'][$i]['saleInfo']['saleability'], "<br /> ";
   
   if(isset($data['items'][$i]['accessInfo']['pdf']['downloadLink'])){

   echo "<strong><font color=red>Free Pdf Available: </font></strong>  <a href=".$data['items'][$i]['accessInfo']['pdf']['downloadLink'].">Click-To-View</a> <br /> ";
   }
   if(isset($data['items'][$i]['volumeInfo']['description'])){
   echo "<strong><font color=red>Description:</font></strong>" .$data['items'][$i]['volumeInfo']['description'], "<br /> <br /><br />";
   }
   $cntr++;
}
?>

//Screenshot


Friday, December 2, 2016

Pie Chart Using Google Chart


///////////////////////////////////////////////////////////////////////////////////////////////////
//// index.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
include("pdo.php");
$obj=new DB;
$row=$obj->geTable();

?>

<html>
  <head>
    <script type="text/javascript" src="loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);
   
 function drawChart() {
      new google.visualization.PieChart(document.getElementById('routinechart')).draw(google.visualization.arrayToDataTable(<?php echo $row?>), {
            'legend':'center',
            'title':'360 Spectrum of my routine!',
'colors': ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6'],
                     'width':900,
                     'height':900,
'is3D': true});
      }
    </script>
  </head>
  <body>
    <div id="routinechart" style="width: 900px; height: 900px;"></div>
  </body>
</html>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End index.php
///////////////////////////////////////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////////////////////////////
//// pdo.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
//connecting database using pdo
//$obj=new DB;
//$obj->geTable1();
//$obj->geTable();
//print_r($x);
class DB{

private $hostname;
private $username;
private $password;
private $dbname;

      function __construct(){
   $this->hostname='localhost';
$this->username='root';
$this->password='';
$this->dbname="chart";
 }
/* function geTable1(){
echo "good to go";
}  
*/function geTable(){
     $this->connect();
     $dbh=$this->dbh;
     $sql = "SELECT * FROM activity";
$res[]=array("Task", "Hours per Day");
foreach ($dbh->query($sql) as $row)
    {
//$res[]=$row["task"]." , ". $row["hourperday"];
//["Work , 11","Eat , 2","Commute , 3","Watch TV , 4","Walk , 2","Teach , 3","Sleep , 3"]DT634ER6 T
   // echo $row["task"] ." - ". $row["hourperday"] ."<br/>";
 //  ["Work,11","Eat,2","Commute,3","Watch TV,4","Walk,2","Teach,3","Sleep,3"]
   
    //['Task', 'Hours per Day'],['Work',     11],
 $res[]=array($row["task"],$row["hourperday"]);
    }
$x=json_encode($res,JSON_NUMERIC_CHECK);
//print_r($x);
return $x;

}
function connect(){
try {
    $dbh = new PDO("mysql:host=$this->hostname;dbname=$this->dbname",$this->username,$this->password);

    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
    //echo 'Connected to Database<br/>';
   
    $this->dbh=$dbh;
    $dbh = null;
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
}
}
?> 

///////////////////////////////////////////////////////////////////////////////////////////////////
//// End pdo.php
///////////////////////////////////////////////////////////////////////////////////////////////////

Thursday, December 1, 2016

Youtube API Searching By Name and Customizing the Details Obtained!


<div  align="center">
  <body>
    <form method="GET">
  <table>
  <tr><td>Search Term: <input type="text" id="q" name="q" placeholder="Enter Search Term"></td></tr>
  <tr><td> Max Results: <input type="number" id="maxResults" name="maxResults"  step="1" placeholder="Enter Search No."></td></tr>

  <tr><td> <input type="submit" value="Search"></td></tr>
  </table>
</form>
<h3>Videos</h3>
</body>
</div>





<?php
/**********************************************************************************/
?>




<script>
function detail(i){
var lngdscp=document.getElementById("discplg"+i).innerHTML;
var stdscp=document.getElementById("discpst"+i).innerHTML;

var x =document.getElementById("descp"+i).innerHTML;

  if(x=="More&gt;&gt;"){
 x=document.getElementById("descp"+i).innerHTML="Less&lt;&lt;";
  document.getElementById("discp"+i).innerHTML=lngdscp;
  }
  else{
      x=document.getElementById("descp"+i).innerHTML="More&gt;&gt;";
 document.getElementById("discp"+i).innerHTML=stdscp;
  }
}
function abc(x){
document.getElementById("myframe").src="https://www.youtube.com/embed/"+x+"?showinfo=0";
}
</script>




<?php
/**********************************************************************************/


$apikey ='Wamyyyjjjj00000mutguiopred90mmmopred'; //replace it with your own
if(isset($_GET['q'])){
$searchTerm=urlencode($_GET['q']);
}
else{
$searchTerm="abcd";
}


if(isset($_GET['maxResults'])){
$maxResults=$_GET['maxResults'];
}
else{
$maxResults=5;
}
$maxResults;
$url = "https://www.googleapis.com/youtube/v3/search?part=id&maxResults=10&q=".$searchTerm."&type=video&key=".$apikey;
$ch=curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$body=curl_exec($ch);
curl_close($ch);

$data=json_decode($body,true);
echo "<div align='center'>";
echo"<table boder='1'>";

echo"<tr><td colspan='2' align='center'>";
$videoid1= $data['items'][0]['id']['videoId'];
echo'<iframe id="myframe" width="560" height="315" src="https://www.youtube.com/embed/'.$videoid1.'?showinfo=0" frameborder="0" allowfullscreen></iframe>';
echo"</td></tr>";
$output='';
for($i=0; $i<$maxResults; $i++){
$videoid=$data['items'][$i]['id']['videoId'];

$url2 = "https://www.googleapis.com/youtube/v3/videos?id=".$videoid."&key=".$apikey."&part=snippet,statistics,status&fields=items(snippet(publishedAt,title,channelTitle,description,thumbnails(default(url))),status(privacyStatus),statistics(viewCount,likeCount,dislikeCount,commentCount))";

//Fetching the data using CURL
$ch=curl_init($url2);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$body2=curl_exec($ch);
curl_close($ch);

$data2=json_decode($body2,true);


//Displaying the result
echo'<tr><td><a href="javascript:void(0)" onclick="abc(\''.$videoid.'\')"><img src="' . $data2['items'][0]['snippet']['thumbnails']['default']['url'] . '" alt="error"></a></td></tr>';

echo "<tr><td width='500'><strong><font color=red>Channel Title:</font></strong>".$data2['items'][0]['snippet']['channelTitle']."</td></tr>";

echo"<tr><td width='500'><strong><font color=red>Title:</font></strong>".$data2['items'][0]['snippet']['title']." ".'<br> <strong><font color=red>Date Published:</font></strong>'.$data2['items'][0]['snippet']['publishedAt']."</td></tr>";
echo "<tr><td width='500'><strong><font color=red>No.of view:</font></strong>".$data2['items'][0]['statistics']['viewCount']."</td></tr>";
echo "<tr><td width='500'><strong><font color=red>No.of like:</font></strong>".$data2['items'][0]['statistics']['likeCount']."</td></tr>";
echo "<tr><td width='500'><strong><font color=red>No.of Dislike:</font></strong>".$data2['items'][0]['statistics']['dislikeCount']."</td></tr>";
echo "<tr><td width='500'><strong><font color=red>No.of Comment:</font></strong>".$data2['items'][0]['statistics']['commentCount']."</td></tr>";
echo "<tr><td width='500'><strong><font color=red>Privacy Status:</font></strong>".$data2['items'][0]['status']['privacyStatus']."</td></tr>";

$description=$data2['items'][0]['snippet']['description'];
$myarray=array();
$myarray=explode(" ",$description);
count($myarray);
if(count($myarray)>10){
$num=10;
}
else{
$num=count($myarray);
}
$st="";

   for($j=0;$j<$num;$j++){
   $st.=$myarray[$j];
   $st.=" ";
   }

echo"<div id='discplg".$i."' style='display:none'>".$description."</div>";
echo "<div id='discpst".$i."' style='display:none'>".$st."</div>";



echo "<tr><td width='500'><strong><font color=red>Description:</font></strong><div id='discp".$i."'>".$st."</div><a id='descp".$i."' href='javascript:void(0)' onclick='detail($i)'>More>></a></div></td></tr>";



}
echo"</table>";
echo "</div>";

?>