jQgrid wrong pager structure - php

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

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.

HTML and PHP pagination not working correctly

I have a bit of code that pulls all the results from a database and displays the ones that are relevant to the users search. I have some more code that counts the amount of items and generates a certain amount of pages based on how many items are relevant to the users search. The problem is as follows. If I do a search all, my code displays everything in the database on 11 pages. If I search for car, it will still display 11 pages but only 2 results that have the word car in the title. The problem is that these results display on the eighth page and all other pages are blank. During the search all the two results with car in the title displayed on the eighth page as well. The search all is based on the order the items are in, in the database. Here is my current code:
$pagesQuery = mysql_query("SELECT count(id) FROM(`posts`)");
$pageNum = ceil(mysql_result($pagesQuery, 0)/5);
$start = (($page-1)*5);
$currentname = mysql_query("SELECT * FROM posts LIMIT $start, 5");
while ($row = mysql_fetch_array($currentname)) {
//recieve relevant data.
$title = $row[0];
$desc = $row[13];
$ID = $row[6];
$views = $row[3];
$user = $row[7];
//fetch the last id from accounts table.
$fetchlast1 = mysql_query("SELECT * FROM allaccounts WHERE id=(SELECT MAX(id) FROM allaccounts)");
$lastrow1 = mysql_fetch_row($fetchlast1);
$lastid1 = $lastrow1[6];
//acquire the username of postee.
for ($i1=1; $i1 <= $lastid1; $i1++) {
$currentname1 = mysql_query("SELECT * FROM allaccounts WHERE id=$user");
while ($row1 = mysql_fetch_array($currentname1)) {
$username1 = $row1[0];
}
}
//Format Title, description and view count.
$title2 = rtrim($title);
$donetitle = str_replace(" ", "-", $title2);
$url = "articles/".$ID."/".$donetitle."";
$donetitle = strlen($title) > 40 ? substr($title,0,40)."..." : $title;
$donedesc = '';
if(strlen($desc) > 150) {
$donedesc = explode( "\n", wordwrap( $desc, 150));
$donedesc1 = $donedesc[0] . '...';
}else{
$donedesc1 = $desc;
}
$finviews = number_format($views, 0, '.', ',');
//Give relevant results
if(stripos($title, $terms) !== false || stripos($desc, $terms) !== false || stripos($username1, $terms) !== false){
if($row[10] == null){
$SRC = "img/tempsmall.jpg";
}else{
$SRC ="generateThumbnailSmall.php?id=$ID";
}
echo "<div id = \"feature\">
<img src=\"$SRC\" alt = \"article thumbnail\" />
</div>
<div id = \"feature2\">
$donetitle
<p id=\"resultuser\" >$username1</p>
<p id=\"resultp\">$donedesc1</p>
<img src=\"img/icons/flag.png\"/><b id=\"resultview\">$finviews views</b>
</div>
<div id = \"border\"></div>";
}
}
$totalPages = $pageNum;
$currentPage = $page;
$numPagesToShow = 10;
if($currentPage > $totalPages) {
$currentPage = $totalPages;
}
if($numPagesToShow >= $totalPages) {
$numMaxPageLeft = 1;
$numMaxPageRight = $totalPages;
} else {
$pagesToShow = ceil($numPagesToShow/2);
$numMaxPageLeft = $currentPage - $pagesToShow;
$numMaxPageRight = $currentPage + $pagesToShow;
if($numMaxPageLeft <= 0) {
$numMaxPageRight = $numMaxPageRight - $numMaxPageLeft +1;
$numMaxPageLeft = 1;
} elseif($numMaxPageRight >= $totalPages) {
$numMaxPageLeft -= ($numMaxPageRight - $totalPages);
$numMaxPageRight = $totalPages;
}
}
for ($i=$numMaxPageLeft; $i<=$numMaxPageRight; $i++) {
echo "<a id =\"pagenationlink\" href=\"searchresults.php?search=".$terms."&page=".$i."\">".$i."</a>";
}
How can I only display one page with the two results on it instead of 11 pages with the two relevant results on the eighth page? Thanks
Please update your code as below.
But try to use mysqli_() as mysql() are depricted
$cond = "";
if(!empty($_POST["search"]))
{
$cond = " write your search condition " ;
}
$start = (($page-1)*5);
$query = mysql_query("SELECT SQL_CALC_FOUND_ROWS * FROM posts where $cond LIMIT $start, 5");
$TotalDataQuery = mysql_query("SELECT FOUND_ROWS() tot;");
$rsVal = mysql_fetch_array($pagesQuery);
$pagesQuery = $rsVal['tot'];
$pageNum = ceil($pagesQuery/5);
while ($row = mysql_fetch_array($query)) {
//continue your code
}

Datagrid pagination, serverside easyui doesn't work

I am working with datagrid EasyUI, and I want to do a pagination.
In Datagrid displays only 10 row, a shows me 'Displaying 1 to 10 of 10 items'.
I don't know if the output array it's ok, to send to Datagrid.
Here is my code:
public function get_temperatura_humedad_list($page, $rows) {
$offset = ($page - 1) * $rows;
$result = array();
$rs = $this->db->consulta("select count(*) from dht22");
$row = mysqli_fetch_row($rs);
$result['total'] = $row[0];
$rs = $this->db->consulta("select * from dht22 limit $offset, $rows");
$items = array();
while ($row = mysqli_fetch_object($rs)) {
array_push($items, $row);
}
// $result["rows"] = $items;
return $result['rows'] = $items;
}
You should define your variable $rows to get the right offset. Something like this :
$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
$offset = ($page-1)*$rows;

Jqgrid Pagination not working due to query

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

Paging in php mysql

I'm trying to make a website with movies in it, everything is fine but i have just 1 little problem,when ever i make a website, i do all work in my local computer test it then I upload the web, the code below is for paging with query it works fine in WAMP (locally). But when I upload the paging code to my web server it says NOT EXIST.
it shows the else part,whats the problem?
<?php
$per_page = 35;
$page = 1;
if (isset($_GET['page']))
{
$page = intval($_GET['page']);
if($page < 1) $page = 1;
}
$start_from = ($page - 1) * $per_page;
$con= mysql_connect("localhost","sarya_asad","Thisisfor123");
mysql_select_db('saryaal_com_movies',$con);
$current_items = mysql_query( "SELECT * FROM `english` LIMIT $start_from, $per_page");
if( mysql_num_rows($current_items) > 0)
{
while($item = mysql_fetch_assoc($current_items))
{
?>
<tr>
<td> <strong><a href="english/english-preview.php?id=<?php echo$item['id']?>" ><?php echo $item['title'] ;?></a> </strong></td>
<td> <strong> <?php echo $item['year'] ;?> </strong></td>
<td> <strong> <?php echo $item['quality'] ;?> </strong> </td>
</tr>
<tr><td>
<?php
}
}
else
{
echo 'this page does not exists';
}
$total_rows = mysql_query("SELECT COUNT(*) FROM `english`");
$total_rows = mysql_fetch_row($total_rows);
$total_rows = $total_rows[0];
$total_pages = $total_rows / $per_page;
$total_pages = ceil($total_pages); # 19/5 = 3.8 ~=~ 4
for($i = 1; $i <= $total_pages; ++$i)
{
echo "<a href='temp2.php?page=$i' class='pagNumActive'>$i</a> ";
}
?>
<?php if($Strkeyword=="" AND $StrLoc=="" AND $StrMinsal=="-1" AND $StrMaxsal=="-1" AND $StrMax_exp=="maximum" AND $Strcategory=="" AND $Strjobtype=="") {
$sql=mysql_query("select * from job where AND status='Active'");
}
$per_page = 5;
$page = 1;
if (isset($_GET['page'])) {
$page = intval($_GET['page']);
if($page < 1) $page = 1;
}
$start_from = ($page - 1) * $per_page;
if($Strkeyword=="" AND $StrLoc=="" AND $StrMinsal=="-1" AND $StrMaxsal=="-1" AND $StrMax_exp=="maximum" AND $Strcategory=="" AND $Strjobtype=="")
{
$current_items=mysql_query("select * from job LIMIT $start_from, $per_page"); } $start_from, $per_page");
if( mysql_num_rows($current_items)>0) { while($arr=mysql_fetch_array($current_items)) {
?>
<?php include("include/result.php") ?>// result u want to display
<?php
}
} else {
echo 'Data does not exists'; }
if($Strkeyword=="" AND $StrLoc=="" AND $StrMinsal=="-1" AND $StrMaxsal=="-1" AND $StrMax_exp=="maximum" AND $Strcategory=="" AND $Strjobtype=="") {
$total_rows=mysql_query("select COUNT(*) from job where AND status='Active'");
}
$total_rows = mysql_query("SELECT COUNT(*) FROM job");
$total_rows = mysql_fetch_row($total_rows);
$total_rows = $total_rows[0];
$total_pages = $total_rows / $per_page;
$total_pages = ceil($total_pages);
# 19/5 = 3.8 ~=~ 4
echo "<div style='margin-left:280px;'>";
echo "Page : ";
for($i = 1; $i <= $total_pages; $i++) {
echo "[<a style='text-decoration:none' href='search_result.php?page=$i' class='pagNumActive'>$i</a> ]";
}
echo "</div>";
?>
This is your problem:
$con= mysql_connect("localhost","sarya_asad","Thisisfor123");
mysql_select_db('saryaal_com_movies',$con);
You need to change the host details. localhost is the local server on your machine.
change this
$start_from = ($page - 1) * $per_page;
to
$start_from = ($page) * $per_page;
you might want to use something like:
$per_page = 35;
$start_from = $page * $per_page - $per_page;
Try this logic for pagination:
Your goal is to offset by the number of images you want to display on each page.
So let's say you want to display 6 movie thumbnails on a page... You'd have:
$videos_per_page = 6
$pageNumber = (isset($_GET['page']) ? ($_GET['page']) : 1);
And your offset would be:
$offset = $videos_per_page * $pageNumber
(6 videos * page 0... so you're offsetting 0 videos. That's good because you want to display the first 6 videos in your data structure on page 0).
So now that you have your offset value... You need to set your array pointer to the correct spot... Loop through your database rows storing your movies and move your pointer by your offset value... Store that in $videos_to_offset...
while ($videos_per_page < $offset && ($row = $Query_Result->fetch_assoc())) {
$videos_to_offset++;
}
Now you can loop through your database rows, outputting your videos from wherever your offset array pointer left off:
$video_counter = 0;
while ($video_counter < $videos_per_page && ($row = $Query_Result->fetch_assoc())) {
echo $row['videopath'];
$video_counter++;
}
Something like that.

Categories