Monday, November 7, 2016

Bar Graph using Highchart PHP and MySQL

///////////////////////////////////////////////////////////////////////////////////////////////////
//// index.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
<script>
$(function () {
//-------------------------------------------
       jQuery.extend({
            getValues: function(url) {
                var result = null;
                $.ajax({
                    url: url,
                    type: 'get',
                    dataType: 'json',
                    async: false,
                    success: function(data) {
   alert(data);
                        result = data;
                    }
                });
               return result;
            }
        });
        var myServerData = $.getValues("data.php"); //direct this to your PHP script and make sure that right JSON is returned
//--------------------------------------------
    $('#container').highcharts({
//------------------------------------
chart: {
                type: 'column'
            },
            title: {
                text: 'Chanel share title'
            },
            subtitle: {
                text: 'percent of channel share'
            },
            xAxis: {
                type: 'category',
                labels: {
                    rotation: -45,
                    align: 'right',
                    style: {
                        fontSize: '13px',
                        fontFamily: 'Verdana, sans-serif'
                    }
                }
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Monthly share of channel'
                }
            },
legend: {
                enabled: false
            },
            tooltip: {
                pointFormat: 'Monthly income: <b>{point.y:.1f} USD</b>',
            },
//---------------------------------------
       
          series: [{
                name: 'Monthly Income',
                data: myServerData,
                dataLabels: {
                    enabled: true,
                    rotation: -90,
                    color: '#FFFFFF',
                    align: 'right',
                    x: 4,
                    y: 10,
                    style: {
                        fontSize: '13px',
                        fontFamily: 'Verdana, sans-serif',
                        textShadow: '0 0 3px black'
                    }
                }
            }]
    });
});

</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 = "charts";

  public $error = "";

  function __construct()
    {
    }

//---------------
//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
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// data.php
///////////////////////////////////////////////////////////////////////////////////////////////////

<?php
include("db.php");
$dbObj=new DB;
$selSql="select * from turnover";
$results=$dbObj->GetChart($selSql);


?>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End data.php
///////////////////////////////////////////////////////////////////////////////////////////////////


Image Cropping Using Jcrop and PHP

///////////////////////////////////////////////////////////////////////////////////////////////////
//// index.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
session_start();
include("functions.php");
if(isset($_REQUEST['action'])){
$path='demos/demo_files/';
$randNo = time();
$thumbImage = $path.'thumb/';
$previewpath = $path.'preview/';
$filename = strtolower($randNo.str_replace(" ","_",$_FILES['uploadimage']['name']));
if(move_uploaded_file($_FILES['uploadimage']['tmp_name'],$path.$filename)) {
chmod($path.'/'.$filename,0777);
createThumbs($path,$thumbImage.'/',167,$filename);
createThumbs($path,$previewpath.'/',382,$filename);
$_SESSION['imagecreationname'] = $filename;
header("location:demos/crop.php");
exit;
}
}
?>


<form action="" method="post" name="frm" enctype="multipart/form-data">
<input type="hidden" name="action" value="trans">
<center>
<input type="file" name="uploadimage" id="uploadimage" onchange="javascript:document.frm.submit()">
</center>
</form>

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

///////////////////////////////////////////////////////////////////////////////////////////////////
//// functions.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
function createThumbs( $pathToImages, $pathToThumbs,$thumbWidth,$fname ) {
 // open the directory
if(!is_dir($pathToThumbs)){
mkdir($pathToThumbs,0777);
}
$dir = opendir( $pathToImages );
// loop through it, looking for any/all JPG files:
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'jpg' ){
 // load image and get image size
 $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
 $width = imagesx( $img );
 $height = imagesy( $img );
 // calculate thumbnail size
 $new_width = $thumbWidth;
 $new_height = floor( $height * ( $thumbWidth / $width ) );

 // create a new temporary image
 $tmp_img = imagecreatetruecolor( $new_width, $new_height );

 // copy and resize old image into new image
 imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

 // save thumbnail into a file
 imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
}

if ( strtolower($info['extension']) == 'png' ){
 // load image and get image size
 $img = imagecreatefrompng( "{$pathToImages}{$fname}" );
 $width = imagesx( $img );
 $height = imagesy( $img );
 // calculate thumbnail size
 $new_width = $thumbWidth;
 $new_height = floor( $height * ( $thumbWidth / $width ) );

 // create a new temporary image
 $tmp_img = imagecreatetruecolor( $new_width, $new_height );

 // copy and resize old image into new image
 imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

 // save thumbnail into a file
 imagepng( $tmp_img, "{$pathToThumbs}{$fname}" );
}

if ( strtolower($info['extension']) == 'gif' ){
 // load image and get image size
 $img = imagecreatefromgif( "{$pathToImages}{$fname}" );
 $width = imagesx( $img );
 $height = imagesy( $img );
 // calculate thumbnail size
 $new_width = $thumbWidth;
 $new_height = floor( $height * ( $thumbWidth / $width ) );

 // create a new temporary image
 $tmp_img = imagecreatetruecolor( $new_width, $new_height );

 // copy and resize old image into new image
 imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

 // save thumbnail into a file
 imagegif( $tmp_img, "{$pathToThumbs}{$fname}" );
}

if ( strtolower($info['extension']) == 'bmp' ){
 // load image and get image size
 $img = imagecreatefromwbmp( "{$pathToImages}{$fname}" );
 $width = imagesx( $img );
 $height = imagesy( $img );
 // calculate thumbnail size
 $new_width = $thumbWidth;
 $new_height = floor( $height * ( $thumbWidth / $width ) );

 // create a new temporary image
 $tmp_img = imagecreatetruecolor( $new_width, $new_height );

 // copy and resize old image into new image
 imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

 // save thumbnail into a file
 imagewbmp( $tmp_img, "{$pathToThumbs}{$fname}" );
}

 // close the directory
 closedir( $dir );
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End functions.php
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// crop.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
session_start();


if ($_SERVER['REQUEST_METHOD'] == 'POST')
{  
    //echo $_SERVER['REQUEST_METHOD']
//;
    $_SESSION['imagecreationname']; //1432926753muna.jpg
   $src='demo_files/'.$_SESSION['imagecreationname'];//demo_files/1432927027book1.jpg
   //print_r($_POST);
//echo "hi";
//POSTArray ( [x] => 195 [y] => 235 [w] => 49 [h] => 49 ) hi

//exit;
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $_POST['w'],$_POST['h'] );//Resource id #4//$targ_w, $targ_h
//print_r($dst_r);
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$_POST['w'],$_POST['h'],$_POST['w'],$_POST['h']);

header('Content-type: image/jpeg');
imagejpeg($dst_r,null,90);
    //echo'<img src="'.$img_r.'" width="700" height="700">';
}

// If not a POST request, display page below:

?>


  <script src="../js/jquery.min.js"></script>
  <script src="../js/jquery.Jcrop.js"></script>


<script type="text/javascript">

  $(function(){

    $('#cropbox').Jcrop({
      aspectRatio: 1,
      onSelect: updateCoords
    });

  });

  function updateCoords(c)
  {
    var a=$('#x').val(c.x);
    var b=$('#y').val(c.y);
//alert(c);
//alert(a);
//alert(b);
    $('#w').val(c.w);
    $('#h').val(c.h);
  };

  function checkCoords()
  {
    if (parseInt($('#w').val())) {
alert($('#x').val())//264
alert($('#y').val())//176
alert($('#w').val())//186
alert($('#h').val());//186
return true;
}
    alert('Please select a crop region then press submit.');
    return false;
  };

</script>
<style type="text/css">
  #target {
    background-color: #ccc;
    width: 500px;
    height: 330px;
    font-size: 24px;
    display: block;
  }


</style>

</head>
<body>
<?php
if(trim($_SESSION['imagecreationname'])!=''){
?>
<!-- This is the image we're attaching Jcrop to -->
<img src="demo_files/<?php echo $_SESSION['imagecreationname'] ;?>" id="cropbox" />
<!-- This is the form that our event handler fills -->
<form action="crop.php" method="post" onSubmit="return checkCoords();">
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="submit" value="Crop Image" class="btn btn-large btn-inverse" />
</form>
<?php
}
?>



</body>

</html>

///////////////////////////////////////////////////////////////////////////////////////////////////
//// End crop.php
///////////////////////////////////////////////////////////////////////////////////////////////////




Bar Chart using jpgraph,PHP and MySQL.

///////////////////////////////////////////////////////////////////////////////////////////////////
//// index.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php // content="text/plain; charset=utf-8"
//
require_once ('jpgraph/jpgraph.php');
require_once ('jpgraph/jpgraph_bar.php');

include("db.php");
$obj=new DB;
$sql="select * from icecream";
$obj->getSqlTable($sql);
$products=$obj->arr;
foreach($products as $product){
$montharr[]=$product['month'];
$week1arr[]=$product['week1'];
$week2arr[]=$product['week2'];
$week3arr[]=$product['week3'];
$week4arr[]=$product['week4'];
}

$data1y=$week1arr;
$data2y=$week2arr;
$data3y=$week3arr;
$data4y=$week4arr;

// Create the graph. These two calls are always required
$graph = new Graph(500,350,'auto');
$graph->SetScale("textlin");

$theme_class=new UniversalTheme;
$graph->SetTheme($theme_class);

//$graph->yaxis->SetTickPositions(array(0,30,60,90,120,150), array(15,45,75,105,135));
$graph->SetBox(false);

$graph->ygrid->SetFill(false);
//$graph->xaxis->SetTickLabels(array('Jan','Feb','March','April','May'));
$graph->xaxis->SetTickLabels($montharr);  // 12345
$graph->yaxis->HideLine(false);
$graph->yaxis->HideTicks(false,false);

// Create the bar plots
$b1plot = new BarPlot($data1y);
$b2plot = new BarPlot($data2y);
$b3plot = new BarPlot($data3y);
$b4plot = new BarPlot($data4y);

// Create the grouped bar plot
$gbplot = new GroupBarPlot(array($b1plot,$b2plot,$b3plot,$b4plot));
// ...and add it to the graPH
$graph->Add($gbplot);


$b1plot->SetColor("white");
$b1plot->SetFillColor("#cc1111");

$b2plot->SetColor("white");
$b2plot->SetFillColor("#11cccc");

$b3plot->SetColor("white");
$b3plot->SetFillColor("#1111cc");

$graph->title->Set("Bar Plots");

// Display the graph
$graph->Stroke();
?>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End index.php
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// update.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php


if(isset($_REQUEST['fetchdata'])){
include("db.php");
$obj=new DB;
$sql="select * from icecream";
$obj->getSqlTable($sql);
$products=$obj->arr;


//echo'<pre>';
//print_r($products as $product);
foreach($products as $product){
$montharr[]=$product['month'];
$week1arr[]=$product['week1'];
$week2arr[]=$product['week2'];
$week3arr[]=$product['week3'];
$week4arr[]=$product['week4'];
}
print_r($montharr);
}

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

///////////////////////////////////////////////////////////////////////////////////////////////////
//// db.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php

  class DB{
     private $dbhost = "localhost";
     private $dbuser = "root";
     private $dbpass = "";
     private $dbname = "abc";
public $error='';
/**********************************************
  get sql connection
***********************************************/
public function getCon(){
 $con=mysql_connect($this->dbhost,$this->dbuser,$this->dbpass);
 if(!$con){
 die("cant connect to db");
 }
 mysql_select_db($this->dbname, $con);
 return $con;

}
/**********************************************
get sql row from db
***********************************************/
function getSqlRow($sql){
 $arr=array();
 $con=$this->getCon();
 $result=mysql_query($sql, $con);
 $row=mysql_fetch_array($result);
 mysql_close($con);
      return $row;
}
/**********************************************
get sql table from db
***********************************************/
function getSqlTable($sql){
 $arr=array();
 $con=$this->getCon();
 $result=mysql_query($sql, $con);
 while($row=mysql_fetch_assoc($result)){
 $arr[]=$row;
 }
 mysql_close($con);
     $this->arr=$arr;
}


    /**********************************************
***********************************************/
}
?>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End db.php
///////////////////////////////////////////////////////////////////////////////////////////////////

Getting Sunrise and Sunset Time of a Country Using YQL (Yahoo API)


///////////////////////////////////////////////////////////////////////////////////////////////////
//// index.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
t=document.createElement("Table");
t.setAttribute("border","3");
$(document).ready(function(){
 $.ajax( {
    url: 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.states%20where%20place%3D23424848&format=json&diagnostics=true',
  type: 'POST',
async:false,
       success: function(response) {
pp=document.createElement("tr");
q1=document.createElement("th");
q1.innerHTML="STATENAME";
q2=document.createElement("th");
q2.innerHTML="SUNRISE";
q3=document.createElement("th");
q3.innerHTML="SUNSET";
pp.appendChild(q1);
pp.appendChild(q2);
pp.appendChild(q3);
t.appendChild(pp);
console.log(response);
v=response.query.results.place;
l=v.length;
for(i=0;i<l;i++)
{
statename=v[i].name;
placeid=v[i].woeid;
z=document.createElement("tr");
y=document.createElement("td");
y.innerHTML=statename;
z.appendChild(y);

console.log(statename);
rrr="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D"+placeid+"&format=json&diagnostics=true";
$.ajax( {
url: rrr,
async:false,
success: function(datareturned) {

console.log(datareturned);
sunrisetime=datareturned.query.results.channel.astronomy.sunrise;
y1=document.createElement("td");
y1.innerHTML=sunrisetime;
sunsettime=datareturned.query.results.channel.astronomy.sunset;
y2=document.createElement("td");
y2.innerHTML=sunsettime;
z.appendChild(y1);
z.appendChild(y2);
t.appendChild(z);
}
});
}

document.getElementsByTagName("body")[0].appendChild(t);}
    });
});

</script>
</head>
<body>
</body>
</html>



</html>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End index.php
///////////////////////////////////////////////////////////////////////////////////////////////////

Pagination using JQuery and php

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


<?php
$Limit=10;
$setLimit=0;
include("db.php");
$dbObj=new DB;
$sql="select * from category limit $setLimit,$Limit";
$results=$dbObj->GetSqlTable($sql);

$countsql="select * from category";
$numrow=$dbObj->GetSqlTable($countsql);
 $numRow=count($numrow);//183
 $numPage=ceil($numRow/$Limit);//19
//echo'<pre>';print_r($results);

?>
Show<select onchange="loadPagi(this.value)" align="left" id="loadppagi">
<?php for($i=10; $i<=100; $i+=10){?>
<option value="<?php echo $i ?>"><?php echo $i ?></option>
<?php }?>

</select>Entries



<h3 align="center" style="color:#FF0066">Muna Pagination</h3>
<div id="displayTable">
<table align="center" border="1" cellpadding="1" style="background-color:#CCFF33" width="60%">
<tr>
<th>ID</th>
<th>Category Name</th>
<th>Category Order</th>
<th colspan="2">Action</th>
</tr>
<?php foreach($results as $result){?>
<tr>
<td><?php echo $result['id']; ?></td>
<td><?php echo $result['cat_name']; ?></td>
<td><?php echo $result['category_order']; ?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php }?>
</table>

<div align="center">

<?php for($i=1; $i<=$numPage;$i++){?>
<button "javascript:void(0)" onclick="midPages(<?php echo $i?>)" style="background-color:#FF99FF"><?php echo $i?></button>
<?php }?>
<button "javascript:void(0)" onclick="nextPages(1)" style="background-color:#CC33FF">Next</button>
</div>
</div>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
   function onPage(p){
     alert(p);
 var limit=$("#loadppagi").val();
      $.ajax({
      type:"POST",
 url:"middle.php",
 data:{"limit":limit,"pageno":p},
 success:function(data){
   $("#displayTable").html(data);
 }
     });
   }
  function firstPages(f){
 
 var limit=$("#loadppagi").val();
alert(f);
     $.ajax({
 type:"POST",
 url:"middle.php",
 data:{"pageno":f,"limit":limit},
 success:function(data){
    $("#displayTable").html(data);
 }
 });
 
  }

   function lastPages(l){
 
 var limit=$("#loadppagi").val();
//alert(f);
     $.ajax({
 type:"POST",
 url:"middle.php",
 data:{"pageno":l,"limit":limit},
 success:function(data){
    $("#displayTable").html(data);
 }
 });
 
  }
   function nextPages(n){
   
      n++;
 alert(n);
 var limit=$("#loadppagi").val();
//alert(limit);
     $.ajax({
 type:"POST",
 url:"middle.php",
 data:{"pageno":n,"limit":limit},
 success:function(data){
    $("#displayTable").html(data);
 }
 });
 
   }
   function prevPages(p){
     alert(p);
p--;
 var limit=$("#loadppagi").val();
//alert(limit);
     $.ajax({
 type:"POST",
 url:"middle.php",
 data:{"pageno":p,"limit":limit},
 success:function(data){
    $("#displayTable").html(data);
 }
 });
 
   }
   function midPages(i){
     var limit=$("#loadppagi").val();
alert(limit);
     $.ajax({
 type:"POST",
 url:"middle.php",
 data:{"pageno":i,"limit":limit},
 success:function(data){
    $("#displayTable").html(data);
 }
 });
   }
 
   function loadPagi(t){
   var pageno=1;
   alert(pageno);
   $.ajax({
      type:"POST",
 url:"middle.php",
 data:{"limit":t,"pageno":pageno},
 success:function(data){
   $("#displayTable").html(data);
 }
 
   });

   }
</script>

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

///////////////////////////////////////////////////////////////////////////////////////////////////
//// fetchmiddle.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php




if(isset($_REQUEST['limit'])){
   $Limit=$_REQUEST['limit'];
}
else {$Limit=10;}

if(isset($_REQUEST['pageno'])){
  $pageno=$_REQUEST['pageno'];
  $setLimit=($pageno-1)*$Limit;
}
else{$setLimit=0;}
include("db.php");
$dbObj=new DB;
$sql="select * from category limit $setLimit,$Limit";
$results=$dbObj->GetSqlTable($sql);

$countsql="select * from category";
$numrow=$dbObj->GetSqlTable($countsql);
 $numRow=count($numrow);//183
 $numPage=ceil($numRow/$Limit);//19


?>
     <table align="center" border="1" cellpadding="1" style="background-color:#FFCCFF" width="60%">
<tr>
<th>ID</th>
<th>Category Name</th>
<th>Category Order</th>
<th colspan="2">Action</th>
</tr>
<?php foreach($results as $result){?>
<tr>
<td><?php echo $result['id']; ?></td>
<td><?php echo $result['cat_name']; ?></td>
<td><?php echo $result['category_order']; ?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php }?>
</table>      
             
                <div align="center">
<button "javascript:void(0)" onclick="firstPages(1)" style="background-color:#CC33FF">First</button>
<?php if($pageno>1){?>
<button "javascript:void(0)" onclick="prevPages(<?php echo $pageno?>)" style="background-color:#CC33FF">Prev</button>
<?php } ?>
<?php for($i=1; $i<=$numPage;$i++){?>
<button "javascript:void(0)" onclick="midPages(<?php echo $i?>);" style="background-color:#FF99FF"><?php if($i==$pageno){?> <font style="color:#FF0000" style="background-color:#FF9900"><strong><?php }?> <?php echo $i?></strong></font></button>
<?php }?>
 <?php if($pageno<$numPage){?>
<button "javascript:void(0)" onclick="nextPages(<?php echo $pageno?>)" style="background-color:#CC33FF">Next</button>
 <?php } ?>
<button "javascript:void(0)" onclick="lastPages(<?php echo $numPage?>)" style="background-color:#CC33FF">Last</button>
Page
   <select onchange="onPage(this.value)" align="left" id="onPage">
<?php for($i=1; $i<=$numPage;$i++){?>
<option value="<?php echo $i ?>"><?php echo $i ?></option>
<?php }?>

</select>
<br/>Showing Page: <?php echo $pageno?> of <?php echo $numPage?>
</div>
</div>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End fetchmiddle.php
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// db.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
///////////////////////////////////////////////////////////////////////////////////////////////////
//// Digimagination Systems 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 = "ecommerce";

  public $error = "";

  function __construct()
    {
    }

//---------------
//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;
}
//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_array($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!");
}
//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 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
///////////////////////////////////////////////////////////////////////////////////////////////////

Autocomplete Using Jquery & PHP

///////////////////////////////////////////////////////////////////////////////////////////////////
//// index.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function abc(){
var minlength=2;

    var chk=document.getElementById("country_name").value;
   if(chk.length>=minlength){
   $.ajax({
 type:"POST",
 url:"fetchresult.php",
 data:{"hints":chk},
 success:function(data){
 $("#hints").html(data)
 }

});
   }

}
</script>


<form action="#" method="post">
<table>
<tr>
  <td>
    <input type="text" id="country_name" name="country_name" onkeyup="javascript:abc()" />
<div><ul id="hints"></ul></div>
  </td>
</tr>

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

<?php
  if(isset($_REQUEST['sub'])){
    echo "comming here";
  }
?>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End index.php
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// fetchresult.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
include("db.php");
$obj=new DB;
$hints="in";
//$obj->hc($sql);tbl_country where countryname LIKE
$hints=$_REQUEST['hints'];
$sql="select * from tbl_country where countryname LIKE  '%$hints%'";
 //echo $sql="select * from tbl_country where countryname LIKE '%$hints%' order by id asc limit 1,10";
$results=$obj->getTable($sql);
  foreach($results as $res){
     echo '<li>'.$res['countryname'].'</li>';
  }



?>
///////////////////////////////////////////////////////////////////////////////////////////////////
//// End fetchresult.php
///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////
//// db.php
///////////////////////////////////////////////////////////////////////////////////////////////////
<?php
class DB{
   private $dbhost="localhost";
   private $dbuser="root";
   private $dbpass="";
   private $dbname="countrysql";






public function hc($sql,$ch){
  $result=mysql_query($sql,$this->getCon());
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']);
}
}
//$res=json_encode($resarr, JSON_NUMERIC_CHECK);
return $resarr;
}





 public function getTable($sql){
  $result=mysql_query($sql,$this->getCon());
while($row=mysql_fetch_array($result)){
 $resarr[]=$row;
}
return $resarr;
 }



  public function getCon(){
  $con=mysql_connect($this->dbhost,$this->dbuser,$this->dbpass);
  mysql_select_db($this->dbname,$con)or
  die(mysql_error("can't connect db"));
  return $con;
 }


}//class end

///////////////////////////////////////////////////////////////////////////////////////////////////
//// End db.php
///////////////////////////////////////////////////////////////////////////////////////////////////