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>";

?>




Tuesday, November 29, 2016

E-Commerce Website Using PHP!

Customer can view the collection and browse through different category of pearl  jewelry, can view new arrival, can short the jewelry by price and color, can search the product by name, can place an order and track it from a wide range of designs available online.

///////////////////////////////////////////////////////////////////////////////////////////////////
//// index.php
///////////////////////////////////////////////////////////////////////////////////////////////////

<style>
#header:hover{
background-color:#00CCFF;
font-weight:bold}

#pimg:hover{background-color:#FF66CC}
</style>


<?php
session_start();
include("db.php");
$obj=new DB;
//-----------header--------------------------------
$sql="select * from category";
$cats=$obj->GetSqlTable($sql);
$numcat=count($cats);
//------------old-------------------------------
unset($_SESSION['numofprotodisp']);
//--New----------------------------------------

if(isset($_REQUEST['id'])){
$id=$_REQUEST['id'];}
else
$id=1;
$sql="select * from product where cat_id=".$id." limit 0,6";
$prods=$obj->GetSqlTable($sql);
$numpro=count($prods);


$sql="select * from product where cat_id=".$id;
$fullpro=$obj->GetSqlTable($sql);
$num=count($fullpro);
$_SESSION['numpro']=$num;
$round=ceil($num/3);
//----------end new-------------------------
?>

<table>
<!--header-->
  <tr>
        <table bgcolor="#FF3366" width="100%" border="1" cellpadding="1" cellspacing="1">
<h2 align="center"><font color="#660033">THE ECCOMERCE SITE</font></h2>
 <tr>
 <?php for($i=0;$i<$numcat;$i++){?>
 <td align="center" id="header" height="40" align="center"><a href="index.php?id=<?php echo $cats[$i]['cat_id']?>"><?php echo ucfirst($cats[$i]['cat_name'])?></a></td>
 <?php }?>
 </tr>
 </table>
 <?php $total=0;
 if(isset($_SESSION['cart'])){
 foreach($_SESSION['cart'] as $key=>$val)
   { $total=$total+$val;}
 }
 // onClick="window.location='mycart.php'"
 ?>
 <img src="icons/mycart.png" align="right" width="70" height="70" onClick="window.location='mycart.php'"/><br/><br/><br/><br/>
 <div id="mycart" align="right" onClick="window.location='mycart.php'">My Cart(<?php echo $total;?>)</div>
  </tr>
  <!--header end-->
                       <h3  align="center"><strong>Muna Practice of Pagination</strong></h3>
  <div align="center">

  Category:<select onchange="byCat(this.value)">
   <option value="" "selected='selected'">Categories</option>
   <?php foreach($cats as $cat){?>
  <option value=" <?php echo $cat['cat_id']?>"> <?php echo $cat['cat_name']?></option>
   <?php }?>
  </select>
  Sort:<select onchange="sortby(this.value)">
   <option value="" "selected='selected'">Sort By</option>
  <option value="DESC">High to Low</option>
  <option value="ASC">Low to High</option>
  </select>
  Classification:<select onchange="selClassif(this.value)">
   <option value="" "selected='selected'">Select Classif</option>
  <option value="PARTY">PARTY</option>
  <option value="FESTIVE">FESTIVE</option>
  <option value="YOUTH COLLECTION">YOUTH COLLECTION</option>
  <option value="CASUAL">CASUAL</option>
  <option value="WEDDING COLLECTION">WEDDING COLLECTION</option>
  <option value="FOR MOMS">FOR MOMS</option>
  <option value="CORPORATE COLLECTION">CORPORATE COLLECTION</option>
  </select>
  Price:<select onchange="selPrice(this.value)">
   <option value="" "selected='selected'">Select Price</option>
  <option value="0-1000">Below 1000</option>
  <option value="1000-1200">1000-1200</option>
  <option value="1201-1400">1201-1400</option>
  <option value="1401-1600">1401-1600</option>
  <option value="1601-1800">1601-1800</option>
  <option value="1800-3000">Above 1800</option>
  </select><br/>
  Showing<select id="numofitem" onchange="loadPagi(this.value)">
    <?php for($i=3;$i<=$num+3;$i+=3){?>
      <option value="<?php echo $i;?>"><?php echo $i;?></option>
      <?php }?>
  </select>Entries Per Page:
  </div>
<!--body-->

     <div id="dynpart">
      <table border="1" cellpadding="1" cellspacing="1" align="center">
     <?php
 for($i=0;$i<$numpro;$i++){
 $coltd="";
 if($i%3==0){
 $r=3;
     echo'<tr>';
 }
 //$prods[$i]['prod_id']
 $coltd.="<td id='pimg'><img src='snaps/".$prods[$i]['image']."' width='200' height='200' onclick=\"window.location='enlarge.php?id=".$prods[$i]['prod_id']."'\"><br/>";
 $coltd.=$prods[$i]['name']."<br/>";
 $coltd.="$".$prods[$i]['price'];
 //dynamic portion
       $flag=0;
       if(isset($_SESSION['cart'])){
         foreach($_SESSION['cart'] as $key=>$val){
           if($key==$prods[$i]['prod_id']){  //many key but one i like 1001
        $flag=1;
           }
     }
  }
 if($flag==1){
 $coltd.="<img  id='cartimg_".$prods[$i]['prod_id']."' src='icons/removecart.jpg' width='70' height='20' align='right' onclick='cartfun(".$prods[$i]['prod_id'].")'>";
 }
 else{
 $coltd.="<img  id='cartimg_".$prods[$i]['prod_id']."' src='icons/addtocart.jpg' width='70' height='20' align='right' onclick='cartfun(".$prods[$i]['prod_id'].")'>";
 }

//dynamic portion end
 $coltd.="</td>";
 echo $coltd;
 $r--;
 if($r==0){
  echo'</tr>';
 }
 
  }
  ?>
  </table>

<!--body end-->
<!--footer-->
   <div id="pagi" align="center">
 <!--dynamic end-->

 <?php
 for($i=1;$i<=3;$i++){
 ?>


<button style="background-color:#33FFCC"  onclick="anyPage(<?php echo $i;?>)"><?php if($i==1){?><font color="#CC0000"; size="+2"><?php echo $i;?></font> <?php } else {echo $i;}?></button>
 <?php }?>

 <a href="javascript:void(0)" onclick="anyPage(<?php echo 1+1;?>)"><img src="icons/Next.png" height="30" width="30" /></a>
 <a href="javascript:void(0)" onclick="anyPage(<?php echo $round;?>)"><img src="icons/Last.png" height="30" width="30" /></a><br/>
  Showing 0 -10 of <?php echo $_SESSION['numpro'];?> Products
 </div>

 </div>

             


<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
 //global var decl
function loadPagi(numofprotodisp){
// alert(numofprotodisp);
var numofprotodisp=$("#numofitem").val();
 $.ajax({
    type:"POST",
url:"update.php",
data:{"page":1,"numofprotodisp":numofprotodisp},
success:function(data){
$("#dynpart").html(data)
}

 });
}


function anyPage(p){
 $.ajax({
    type:"POST",
url:"update.php",
data:{"page":p},
success:function(data){
$("#dynpart").html(data)
}

 });
}


 function cartfun(id){

  if($("#cartimg_"+id).attr("src")=="icons/addtocart.jpg"){
  $("#cartimg_"+id).attr("src","icons/removecart.jpg");
  var action="add";
  }
  else{
   $("#cartimg_"+id).attr("src","icons/addtocart.jpg");
   var action="remove";

  }
  $.ajax({
  url:"updatecart.php",
  type:"POST",
  data:{"action":action,"id":id},
  success:function(data){
    $("#mycart").html("My cart("+data+")");
  }
  });
 }

 function selPrice(price){
 alert(price);
  $.ajax({
    type:"POST",
url:"update.php",
data:{"price":price},
success:function(data){
$("#dynpart").html(data)
}

 });
 }

  function selClassif(clasif){
 alert(clasif);
  $.ajax({
    type:"POST",
url:"update.php",
data:{"clasif":clasif},
success:function(data){
$("#dynpart").html(data)
}

 });
 }
   function sortby(sortval){
 alert(sortval);
  $.ajax({
    type:"POST",
url:"update.php",
data:{"sortval":sortval},
success:function(data){
$("#dynpart").html(data)
}

 });
 }


  function byCat(catid){
 alert(catid);
  $.ajax({
    type:"POST",
url:"update.php",
data:{"catid":catid},
success:function(data){
$("#dynpart").html(data)
}

 });
 }

 </script>

///////////////////////////////////////////////////////////////////////////////////////////////////
//// End index.php
///////////////////////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////////////////////
//// db.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
///////////////////////////////////////////////////////////////////////////////////////////////////
//// Muna ECOMMERCE 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 = "yourdbname";

  public $error = "";

  function __construct()
    {
    }


//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;
}
//by muna
public function GetSqlTable ($sql)
    {
    $data = Array();
    $con = $this->GetDB();
    if (!$con) {return -1;}
    $result = mysql_query($sql, $con);
    if ($result == 0) {return 0;}
    while ($row = mysql_fetch_assoc($result))
//will ignore anything that comes after
{
$data[] = $row;
}
    mysql_close($con);
    return $data;
    }

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;
    }


//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!");
}
$con = $this->GetDB();
$result = mysql_query($sql, $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 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
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// updatecart.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
session_start();
if(isset($_REQUEST['qty'])){
  $qty=$_REQUEST['qty'];
}
$id=$_REQUEST['id'];
$action=$_REQUEST['action'];

switch($action){
case "add":
$total=0;
$_SESSION['cart'][$id]=1;
foreach($_SESSION['cart']as $key=>$val){
$total=$total+$val;
}
echo"$total";
   break;

case "update":
$total=0;
$_SESSION['cart'][$id]=$qty;
foreach($_SESSION['cart']as $key=>$val){
$total=$total+$val;
}
echo"$total";
   break;

case "remove":
$total=0;
unset($_SESSION['cart'][$id]);
foreach($_SESSION['cart']as $key=>$val){
$total=$total+$val;
}
echo"$total";
   break;


}
?>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End updatecart.php
///////////////////////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////////////////////
//// update.php
///////////////////////////////////////////////////////////////////////////////////////////////////



<?php


include("db.php");
$obj=new DB;
session_start();

if(isset($_REQUEST['numofprotodisp'])){
$numofprotodisp=$_REQUEST['numofprotodisp'];
$_SESSION['numofprotodisp']=$numofprotodisp;
}
else
{   if(isset($_SESSION['numofprotodisp']))
    {$numofprotodisp=$_SESSION['numofprotodisp'];}
else
{$numofprotodisp=6;}
}


if(isset($_REQUEST['page'])){
$page=$_REQUEST['page'];
$pageLimit=($_REQUEST['page']-1)*$numofprotodisp;
}
else
{$page=1;
 $pageLimit=1;
}
$numofprotodisp;




//--New----------------------------------------
//echo $numofprotodisp;//9echo $pageLimit;//0
//WHERE column_name BETWEEN value1 AND value2;
//WHERE price BETWEEN ".$p[0]." AND ".$p[1].";


if(isset($_REQUEST['id'])){
       
       $id=$_REQUEST['id'];
     
}
else
{           if(isset($_REQUEST['catid'])){
   $id=$_REQUEST['catid'];
   }
            else
            {$id=1;}
}
$sql="select * from product where cat_id=".$id ;
/***************Price Sort********************************/
if(isset($_REQUEST['price'])){
$price=$_REQUEST['price'];
$p=explode("-",$price);
//echo $p[0];echo $p[1];
$sql.=" and price BETWEEN ".$p[0]." AND ".$p[1];

}

/***************Classif ********************************/
if(isset($_REQUEST['clasif'])){
$clasif=$_REQUEST['clasif'];

$sql.=" and classification ='".$clasif."'";

}
/***************Classif End********************************/
/**************ASC/DESC**************/
if(isset($_REQUEST['sortval'])){
$sortval=$_REQUEST['sortval'];
$sql.=" ORDER BY price ".$sortval;
}
echo $sql.=" limit ".$pageLimit.",".$numofprotodisp;
/***************Price Sort End********************************/

$prods=$obj->GetSqlTable($sql);
$numpro=count($prods);
//----------end new-------------------------

//********************************footer********************************
$sql="select * from product where cat_id=".$id;
$fullpro=$obj->GetSqlTable($sql);
$num=count($fullpro);
$round=ceil($num/$numofprotodisp);
//********************************footer End********************************
?>

      <!--body-->
<h3  align="center"><strong>Next Page</strong></h3>
     <div id="dynpart">
      <table border="1" cellpadding="1" cellspacing="1" align="center">
     <?php
 for($i=0;$i<$numpro;$i++){
 $coltd="";
 if($i%3==0){
 $r=3;
     echo'<tr>';
 }
 //$prods[$i]['prod_id']
 $coltd.="<td id='pimg'><img src='snaps/".$prods[$i]['image']."' width='200' height='200' onclick=\"window.location='enlarge.php?id=".$prods[$i]['prod_id']."'\"><br/>";
 $coltd.=$prods[$i]['name']."<br/>";
 $coltd.="$".$prods[$i]['price'];
 //dynamic portion
       $flag=0;
       if(isset($_SESSION['cart'])){
         foreach($_SESSION['cart'] as $key=>$val){
           if($key==$prods[$i]['prod_id']){  //many key but one i like 1001
        $flag=1;
           }
     }
  }
 if($flag==1){
 $coltd.="<img  id='cartimg_".$prods[$i]['prod_id']."' src='icons/removecart.jpg' width='70' height='20' align='right' onclick='cartfun(".$prods[$i]['prod_id'].")'>";
 }
 else{
 $coltd.="<img  id='cartimg_".$prods[$i]['prod_id']."' src='icons/addtocart.jpg' width='70' height='20' align='right' onclick='cartfun(".$prods[$i]['prod_id'].")'>";
 }

//dynamic portion end
 $coltd.="</td>";
 echo $coltd;
 $r--;
 if($r==0){
  echo'</tr>';
 }
 
  }
  ?>
  </table>

<!--body end-->
    <div id="pagi" align="center">
 <!--dynamic end-->
 <?php

 if($page>1){?>
 <a href="javascript:void(0)" onclick="anyPage(1)"><img src="icons/first.jpg" height="30" width="30" /></a>
 <a href="javascript:void(0)" onclick="anyPage(<?php echo $page-1;?>)"><img src="icons/prev.png" height="30" width="30" /></a>
 <?php }//if end
 for($i=$page-2;$i<=$page+2;$i++){
if($i>=1&& $i<=$round){
 ?>

<button style="background-color:#33FFCC"  onclick="anyPage(<?php echo $i;?>)"><?php if($i==$page){?><font color="#CC0000"; size="+2"><?php echo $i;?></font> <?php } else {echo $i;}?></button>
 <?php }

 }

 $j=$i-2;
 if($j<=$round){
 //echo $round;
 //echo $j;
 //echo $round;//19

 ?>

 <a href="javascript:void(0)" onclick="anyPage(<?php echo $page+1;?>)"><img src="icons/Next.png" height="30" width="30" /></a>
 <a href="javascript:void(0)" onclick="anyPage(<?php echo $round;?>)"><img src="icons/Last.png" height="30" width="30" /></a>
 <?php }?><br/>
 Showing <?php echo $pageLimit;?> -<?php echo $pageLimit+$numofprotodisp;?> of <?php echo $_SESSION['numpro'];?> Products
 </div>

                     <!--end to be sent in next page--->
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End update.php
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// mycart.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
session_start();
include("db.php");
$obj=new DB;
//echo'<pre>'; print_r($_SESSION['cart']);
//foreach($_SESSION['cart'] as $key=>val){}
?>
<table>
 <tr>
        <table border="1" align="center" width="65%">
<h3 align="center"><strong>Displaying the  details of item in your cart!</strong></h3>
   <tr>
   <td align="center" bgcolor="#339933" height="40"><strong>Sln</strong></td>
<td align="center" bgcolor="#339933" height="40"><strong>Product</strong></td>
<td align="center" bgcolor="#339933" height="40"><strong>Quantity</strong></td>
<td align="center" bgcolor="#339933" height="40"><strong>Price</strong></td>
<td align="center" bgcolor="#339933" height="40"><strong>Total</strong></td>
<td align="center" bgcolor="#339933" height="40"><strong>Remove</strong></td>
   </tr>
<?php 
 $cntr=1;
 $totalBuy=0;
 $totalQty=0;
 foreach($_SESSION['cart'] as $key=>$val){
 $totalQty=$totalQty+$val;
 $id=$key;
 $sql="select * from product where prod_id=".$id;
 $prod=$obj->GetSqlTable($sql);
 //echo'<pre>'; print_r($prod);
?>
<tr>
   <td align="center"  bgcolor="#99FFFF"><?php echo $cntr;?>
</td>
<td align="center"  bgcolor="#99FFFF"><img src="snaps/<?php echo $prod[0]['image'];?>" align="center" width="30" height="30" >
</td>
<!-- qty start here-->
<td align="center"  bgcolor="#99FFFF">
<select onchange="update(<?php echo $prod[0]['prod_id'];?>,this.value)">
<?php
for($i=1;$i<$prod[0]['quantity']; $i++){
?>
<option  <?php if($i==$val) echo 'selected="selected"'?>value="<?php echo $i;?>"><?php echo $i;?></option>
<?php }?>
</select>
</td>
   <!-- qty end here-->
<td align="center"  bgcolor="#99FFFF"><?php echo $prod[0]['price'];?>
</td>
   <?php $totalBuy=$totalBuy +$val * $prod[0]['price'];?>
<td align="center"  bgcolor="#99FFFF"><?php echo $val * $prod[0]['price'];?>
</td>
<td align="center"  bgcolor="#99FFFF" ><img src="icons/del.png" align="center" width="25" height="25" >
</td>
 
</tr>
<?php
 $cntr++;
 }
 ?>
<!--Dynamic end-->
 <tr>
   <td colspan="2" align="center" bgcolor="#336633"><strong>Total</strong>
</td>
<td colspan="1" align="center" bgcolor="#336633"><strong><?php echo  $totalQty;?></strong>
</td>
<td colspan="3" align="center" bgcolor="#336633"><strong><?php echo  $totalBuy;?></strong>
</td>
</tr>
 
 <tr>
   <td colspan="6" bgcolor="#CC66CC"> <img src="icons/continue.jpg" align="left" width="80" height="25" onclick="window.location='index.php'"><img src="icons/payment.jpg" align="right" width="80" height="25">
</td>
</tr>
</table>
 </tr>
</table>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
function update(id,val){
  $.ajax({
    url:"midcart.php",
type:"POST",
data:{"action":"update","id":id,"qty":val},
success:function(){
window.location.reload();
}
  });
}
</script>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End mycart.php
///////////////////////////////////////////////////////////////////////////////////////////////////