Jqgrid Pagination not working due to query - php

I am trying to set up a jqgrid and I am having difficulty in constructing the controller that generates the json data to populate the grid. I am using codeigniter 2.0+ and I am not sure how to build the query for php in codeigniter.
I followed this guid under "Loading Data -> JSON Data" for the jqgrid. I also consulted codeigniter docs on data selection. The thing is I am not sure how to write the second query to sort and limit according to the jqgrid paramiters. Here is my controller.
public function applicantdata(){
$page = $this->input->get('page');// get the requested page
$limit = $this->input->get('rows');// get how many rows we want to have into the grid
$sidx = $this->input->get('sidx');// get index row - i.e. user click to sort
$sord = $this->input->get('sord');// get the direction
if(!$sidx){ $sidx =1; }
$this->db->select('*');
$this->db->from('applicant');
$this->db->join('transaction', 'transaction.applicant_id = applicant.id');
$query = $this->db->get();
$count = $query->num_rows();
$limit = 10;
if( $count > 0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages){ $page=$total_pages; }
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
//NOT SURE HOW TO DO THIS IN CODEIGNITER ENVIRONMENT
//$SQL = "SELECT a.id, a.invdate, b.name, a.amount,a.tax,a.total,a.note FROM invheader a, clients b WHERE a.client_id=b.client_id ORDER BY $sidx $sord LIMIT $start , $limit";
//$result = mysql_query( $SQL ) or die("Couldn t execute query.".mysql_error());
$result = $query->result_array();
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
foreach ($result as $myrow){
$responce->rows[$i]['id']=$myrow['id'];
$responce->rows[$i]['cell']=array($myrow['id'],$myrow['firstname'],$myrow['lastname'],$myrow['amount'],$myrow['status']);
$i++;
}
echo json_encode($responce);
}
With the above code, the grid is populating and its is working to a greater extent. Only thing is the pagination stuff not working properly in that the data on page one shows when I move to page 2, 3, etc.

Her is the final working thing. For anyone who may need it.
public function applicantdata(){
$page = $this->input->get('page');// get the requested page
$limit = $this->input->get('rows');// get how many rows we want to have into the grid
$sidx = $this->input->get('sidx');// get index row - i.e. user click to sort
$sord = $this->input->get('sord');// get the direction
if(!$sidx){ $sidx =1; }
$this->db->select('firstname');
$this->db->from('applicant');
$this->db->join('transaction', 'transaction.applicant_id = applicant.id');
$query = $this->db->get();
$count = $query->num_rows();
if( $count > 0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages){ $page=$total_pages; }
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
$this->db->select('*');
$this->db->from('applicant');
$this->db->join('transaction', 'transaction.applicant_id = applicant.id');
$this->db->order_by("applicant.id", $sord);
$this->db->limit($limit, $start);
$query2 = $this->db->get();
$result = $query2->result_array();
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
foreach ($result as $myrow){
$responce->rows[$i]['id']=$myrow['id'];
$responce->rows[$i]['cell']=array($myrow['id'],$myrow['firstname'],$myrow['lastname'],$myrow['amount'],$myrow['status']);
$i++;
}
echo json_encode($responce);
}

Related

jqGrid dataInit doesn't trigger

I'm working with a project that uses jqGrid in the most recent version.
The thing is that this project is PHP(5.6) and uses JSON to "translate/talk" to jqGrid framework, and colModel parameters are all inside PHP arrays. It works flawlessly but i'm unable to trigger dataInit of colModel "criacao" using the actual project's code.
public function laudos($section)
{
$table = 'laudos';
$fields = array('id','laudo','nome_fantasia','cliente','cadastro_id','email','senha','exame','descricao','criacao','exclusao','arquivo');
$tabela = array(
'colNames' => array('ID','Laudo','Clínica','Nome','Cadastro','Email','Senha','Exame','Descrição','Criação','Exclusão','Arquivo'),
'colModel' => array(
array('name'=>'id','hidden'=>true,'search'=>true,'key'=>true),
array('name'=>'laudo','index'=>'laudo','width'=>70,'align'=>'center','search'=>true,'editable'=>true,'editrules'=>array('required'=>true),'sorttype'=>'integer','searchoptions'=>array('sopt'=>'[eq,cn]', 'clearSearch'=>false)),
array('name'=>'nome_fantasia','search'=>true,'width'=>170,'align'=>'center','editable'=>false,'sorttype'=>'text','searchoptions'=>array('sopt'=>'[eq,cn]','clearSearch'=>false),'editrules'=>array('required'=>true)),
array('name'=>'cliente','search'=>true,'width'=>170,'align'=>'center','editable'=>false,'sorttype'=>'text','searchoptions'=>array('sopt'=>'[eq,cn]','clearSearch'=>false),'editrules'=>array('required'=>true),),
array('name'=>'cadastro_id','search'=>true,'hidden'=>true,
'editable'=>true,'edittype'=>'text','searchoptions'=>array('sopt'=>'[eq,cn]','clearSearch'=>false),'editrules'=>array('edithidden'=>true,'required'=>true),
'editoptions'=>array('dataInit'=>'[]')),
array('name'=>'email','search'=>true,'hidden'=>true,'editable'=>true,'sorttype'=>'email','searchoptions'=>array('sopt'=>'[eq,cn]','clearSearch'=>false),'editrules'=>array('edithidden'=>true)),
array('name'=>'senha','search'=>true,'hidden'=>true,'editable'=>true,'editrules'=>array('edithidden'=>true)),
array('name'=>'exame','search'=>true,'width'=>50,'align'=>'center','editable'=>true,'sorttype'=>'text','searchoptions'=>array('sopt'=>'[eq,cn]','clearSearch'=>false),'formatter'=>'select','edittype'=>'select',
'editoptions'=>array('value'=>array('Biópsia'=>'Biópsia','Necrópsia'=>'Necrópsia','Citologia'=>'Citologia'))
),
array('name'=>'descricao','search'=>true,'width'=>200,'align'=>'center','editable'=>true,'sorttype'=>'text','searchoptions'=>array('sopt'=>'[eq,cn]','clearSearch'=>false)),
array('name'=>'criacao','search'=>true,'width'=>70,'formatter'=>'date','fixed'=>true,'resizable'=>false,'align'=>'center','sorttype'=>'date','searchoptions'=>array('sopt'=>'[eq,cn]','clearSearch'=>false), 'editoptions'=>array('dataInit'=>'function (elem) { $(elem).datepicker();')),
array('name'=>'exclusao','search'=>true,'width'=>70,'formatter'=>'date','sorttype'=>'date','fixed'=>true,'resizable'=>false,'editable'=>true,'searchoptions'=>array('sopt'=>'[eq,cn]','clearSearch'=>false),'align'=>'center'),
array('name'=>'arquivo','search'=>false,'width'=>60,'formatter'=>'arquivo','classes'=>'tabela_laudo_arquivo','editable'=>true,'searchoptions'=>array('sopt'=>false,'clearSearch'=>false))
),
'sortname' => 'id',
'caption' => 'Registros de Laudos Cadastrados',
);
This is the PHP function that returns a responce to jqgrid framework:
private function tabelas($table, $fields, $where = '1 = 1')
{
$page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1; // get the requested page
$limit = isset($_REQUEST['rows']) ? $_REQUEST['rows'] : 99999; // get how many rows we want to have into the grid
$sidx = isset($_REQUEST['sidx']) ? $_REQUEST['sidx'] : 'id'; // get index row - i.e. user click to sort
$sord = isset($_REQUEST['sord']) ? $_REQUEST['sord'] : 'desc'; // get the direction
if(!$sidx) $sidx =1;
$count = $this->db->get_var("SELECT COUNT(*) AS count FROM $table WHERE $where");
if($count > 0)
{
$total_pages = ceil($count/$limit);
}
else
{
$total_pages = 0;
}
if ($page > $total_pages) $page = $total_pages;
$start = $limit * $page - $limit; // do not put $limit*($page - 1)
$sql = "SELECT " . implode(',',$fields) . " FROM $table WHERE $where ORDER BY $sidx $sord LIMIT $start, $limit";
$result = $this->db->get_results($sql);
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i = 0;
foreach($result as $row)
{
$responce->rows[$i]['id'] = $row->id;
foreach($fields as $field)
{
$responce->rows[$i]['cell'][] = $row->$field;
}
$i++;
}
return $responce;
}
Using $.extend in my jQGrid script did the job.
Question already answered here.

how to pagify genre search result on the movie database

I have a website that I'm building on my localhost using the MVC design pattern. I have button on click that will display all the genres in TheMovieDatabase which I got using the TheMovieDatabaseAPI. On click of a genre I get data for Page 1 with 20 results. But, I couldn't figure out how to request the results for page 2. These requests are made using PHP.
I am assuming you are taking about pagination using, I am also assuming you are using mySQL as database, I am not sure which framework you are using,
Here is a function i use, you can build around this
function get_movie($page = 1){
global $database_connection;
$start = 0; //Don't modify this
$limit = 10; //set this to 20 to display 20 movies per page
$start = ($page - 1)* $limit;
//get the movie from the table
$sql = "SELECT genre FROM movie_table LIMIT $start, $limit";
$result = mysqli_query($database_connection, $sql);
while ($row = mysqli_fetch_array($result)){
echo "<div>$row['genre']</div>";
}
$movie_rows = mysqli_num_rows (mysqli_query($database_connection ,"SELECT * FROM movie_table"));
$total = ceil($testimony_rows / $limit);
if (isset($page)){
echo "<div>";
echo "<ul class='pager'>";
if($page > 1) {
echo "<a href='?page=".($page - 1)."' style='float: left;' class=' w3-sand w3-btn w3-margin w3-round'>Previous</a>";
}
for($i = 1; $i <= $total; $i++) {
if($i == $page) { echo "<li class='active current'>".$i."</li>"; }
else { echo "<li><a href='?page=".$i."'>".$i."</a></li>"; }
}
if($page != $total) {
echo "<a href='?page=".($page + 1)."' class='w3-btn w3-margin w3-sand w3-round'>Next</a>";
}
echo "</ul></div>";
}
}
you can use limit and offset to get the result for page 2.
Example :- if you are using query builder to get the results
$limit = 20;
$offset = 21;
$queryBuilder->select('d')
->from(<table name>, 'd')
->setMaxResults($limit)
->setFirstResult($offset)
->setParameter('limit', $limit)
->setParameter('offset', $offset);
If you are using raw query :
SELECT * FROM table LIMIT 20 OFFSET 21
Else you can use paginator too
$paginator = new \Doctrine\ORM\Tools\Pagination\Paginator($query);
$totalItems = count($paginator);
$pagesCount = ceil($totalItems / $pageSize);
// now get one page's items:
$paginator
->getQuery()
->setFirstResult($pageSize * ($currentPage-1)) // set the offset
->setMaxResults($pageSize); // set the limit
foreach ($paginator as $pageItem) {
echo "<li>" . $pageItem->getName() . "</li>";
}

PDO pagination query not executed correctly?

I'm currently trying to make some pagination work, but without any success.
The first query I'm executing is to grab all the data needed: so first result should be on the first page, second result on the second and so on... But I'm always getting the first result. Although I copied the query into phpmyadmin to manualy set the query and there it showed me the right results.
Here's the code where everything is happening. I'm stuck why it won't work.
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = 1;
$start = 0;
$query = $db->prepare("SELECT * FROM `users` LIMIT $limit OFFSET $start");
$query->execute();
$result = $query->fetchAll(PDO::FETCH_OBJ);
$count = count($result);
$query2 = $db->prepare("SELECT * FROM `users`");
$query2->execute();
$result2 = $query2->fetchALL(PDO::FETCH_OBJ);
$count2 = count($result2);
// Pagination
$total = ceil($count2 / $limit);
if ($page > 1) {
$start = ($page - 1) * $limit;
}
if ($page != $total) {
$next_page = '<li>»</li>';
} else {
$next_page = '<li class="disabled">»</li>';
}
if ($page > 1) {
$previous_page = '<li>«</li>';
} else {
$previous_page = '<li class="disabled">«</li>';
}
What am I doing wrong?
You are doing nothing with $page. $start is always 0 in the query.
You're going to need to define how many records you want per page, then multiply that by $page -1, e.g.
$start = ($page - 1) * $records_per_page;

jQgrid wrong pager structure

Im trying to parse pager data and grid data through a json response into a jqgrid.
Here is the php file that creates a json file wich contains all these data (pager+grid data)
if(!$sidx) $sidx =1;
$result = mysql_query("SELECT COUNT(*) AS count FROM logs");
$row = mysql_fetch_array($result);
$count = $row['count'];
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
$start = $limit*$page - $limit;
$pages_array = array("page"=> $page , "total" => $total_pages , "records" => $count);
array_push($return_array,$pages_array);
// Getting data for jqGrid table
$data = mysql_query("SELECT * FROM logs ORDER BY log_id DESC");
if(mysql_num_rows($data))
{
while($row = mysql_fetch_array($data))
{
$row_array['rows']['log_id'] = $row['log_id'];
$row_array['rows']['ip'] = $row['ip'];
$row_array['rows']['hostname'] = $row['host'];
$row_array['rows']['log'] = $row['input'];
$row_array['rows']['date'] = $row['date'];
array_push($return_array,$row_array);
}
}
echo json_encode($return_array);
With this php code i retrieve a json file like this :
[{"page":"1","total":2,"records":"34"},
{"rows":{"log_id":"108","ip":"127.0.0.1","hostname":"","log":"having 1=1--","date":"09-06-2013 22:05:57"}},
{"rows":{"log_id":"107","ip":"127.0.0.1","hostname":"","log":"\/\/","date":"09-06-2013 22:05:57"}},
{"rows":{"log_id":"106","ip":"127.0.0.1","hostname":"","log":"**/","date":"09-06-2013 22:05:55"}},
{"rows":{"log_id":"105","ip":"127.0.0.1","hostname":"","log":"+and+","date":"09-06-2013 22:05:55"}}]
But this is wrong structure. In a post here in stackoverflow user Musa said that the structure must be like this :
{
"page": 2,//current page
"total": 2,//number of pages
"records": 11,//# of records in total
"rows": [//array of data
{
"id": "101",//id for this row of data
"cell": [
"101",
"Sundale",
"OTTP",
"652",
"6",
"65",
"656665",
"986346654",
"823343454",
"554332"
]
}
]
}
Can someone help me fix my code so the structure that json response be right ?
Thanks for any help!
So finally i solve this problrm using php's stdClass to load the data and here is the code:
init_mysql();
$response = new stdClass();
// Getting pages number (for jqGrid pager)
if(!$sidx) $sidx =1;
$result = mysql_query("SELECT COUNT(*) AS count FROM logs");
$row = mysql_fetch_array($result);
$count = $row['count'];
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
$start = $limit*$page - $limit;
$response->page = $page;
$response->total = $total_pages;
$response->records = $count;
// Getting data for jqGrid table
$data = mysql_query("SELECT * FROM logs ORDER BY log_id DESC");
$i = 0;
if(mysql_num_rows($data))
{
while($row = mysql_fetch_array($data))
{
$response->rows[$i]['id']=$i+1;
$response->rows[$i]['cell']=array('log_id'=>$row['log_id'],'ip'=>$row['ip'],'hostname'=>$row['host'],'log'=>$row['input'],'date'=>$row['date']);
$i++;
}
}
echo json_encode($response);

Syntax error on pagination

This should be a fairly straight forward question. I am getting a Warning: mysql_num_rows() expects parameter 1 to be resource, boolean error and I can't figure out the correct syntax. Using mysqlerror I am getting You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-5, 5' .
Any help would be great. The code is part of a pagination that I am adding.
Snippet of affected code
<?php
//Number of items to display per page
$perpage = 5;
if(isset($_GET["page"]))
{
$page = intval($_GET["page"]);
}
else
{
$page = 1;
}
$calc = $perpage * $page;
$start = $calc - $perpage;
$result = mysql_query("select * from products Limit $start, $perpage");
$rows = mysql_num_rows($result);
echo mysql_error();
if($rows)
{
$i = 0;
while($post = mysql_fetch_array($result))
{
?>
$start cannot be negative (and it is). You should make sure, that $page is not less than 1. This should fix your problem:
<?php
//Number of items to display per page
$perpage = 5;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
if ($page < 1)
{
$page = 1;
}
$calc = $perpage * $page;
$start = $calc - $perpage;
$result = mysql_query("select * from products Limit $start, $perpage");
$rows = mysql_num_rows($result);
echo mysql_error();
if($rows)
{
$i = 0;
while($post = mysql_fetch_array($result))
{
?>
when you're using LIMIT the value of the starting point should be greater or equal to zero.
LIMIT

Categories