Pagination in codeigniter 3 and send to api - php

I have following function.
public function sendstocktobl()
{
if ($_SERVER['REMOTE_ADDR'] !== $this->localhost) {
echo $_SERVER['REMOTE_ADDR'];
} else {
$this->load->database();
$url = get_integration_url('baselinker');
$this->db->select('user_id');
$this->db->where('bl_send_stock', 1);
$this->db->where('is_baselinker', 1);
$this->db->where('is_active', 1);
$resArr = $this->db->get('ci_users')->result_array();
foreach ($resArr as $row) {
$user_id = $row['user_id'];
$limit = 1000;
$offset = 0;
$where = "quantity is NOT NULL";
$this->db->where($where);
$this->db->where('is_active', 1);
$this->db->where('user_id', $user_id);
$total_results = $this->db->count_all('ci_products');
$total_pages = ceil($total_results / $limit);
$token = get_bl_token($user_id);
$inventoryid = get_bl_inventory($user_id);
$blwh = get_bl_warehouse($user_id);
for ($page = 1; $page <= $total_pages; $page++) {
$arr = [
"inventory_id" => $inventoryid,
"products" => [],
];
$this->db->select('*');
$where = "quantity is NOT NULL";
$this->db->where($where);
$this->db->where('is_active', 1);
$this->db->where('user_id', $user_id);
$prodArr = $this->db->get('ci_products')->result_array();
foreach ($prodArr as $prod) {
$arr['products'][$prod['id']] = [$blwh => $prod['quantity']];
}
$offset += $limit;
}
$preparebl = json_encode($arr);
echo $preparebl;
}
}
}
Long story short, i need to grab data from sql and send to an api for each users which meets some requirements. I need to prepare apicall like this it's now $arr , but the point it's that pagination it's not working, for user 1 i have 1077 records and i get just one json array with products (1077 products), instead of 2 with maximum 1k .
Could someone help me a bit cause i'm not getting where is the error in my script..

Forgotted to add $limit and offset there:
$prodArr = $this->db->get('ci_products')->result_array();
Correct:
$prodArr = $this->db->get('ci_products', $limit, $offset)->result_array();
And added also apicall in "for" loop.
I let here my function which, now it's working fine, maybel it will help someone to inspire.
public function sendstocktobl(){
if ($_SERVER['REMOTE_ADDR'] !== $this->localhost) {echo $_SERVER['REMOTE_ADDR'];}
else{
$this->load->database();
$url = get_integration_url('baselinker');
$this->db->select('user_id');
$this->db->where('bl_send_stock',1);
$this->db->where('is_baselinker',1);
$this->db->where('is_active',1);
$resArr = $this->db->get('ci_users')->result_array();
foreach ($resArr as $row){
$user_id = $row['user_id'];
$limit = 1000;
$offset = 0;
$where = "quantity is NOT NULL";
$total_results = $this->db->where('user_id',$user_id)->where('is_active',1)->where($where)->from("ci_products")->count_all_results();
$total_pages = ceil($total_results / $limit);
$token = get_bl_token($user_id);
$inventoryid = get_bl_inventory($user_id);
$blwh = get_bl_warehouse($user_id);
for ($page = 1; $page <= $total_pages; $page++) {
$arr = [
"inventory_id" => $inventoryid,
"products" => [],
];
$this->db->select('*');
$where = "quantity is NOT NULL";
$this->db->where($where);
$this->db->where('is_active',1);
$this->db->where('user_id',$user_id);
$prodArr = $this->db->get('ci_products', $limit, $offset)->result_array();
foreach($prodArr as $prod){
$arr['products'][$prod['id']] = [$blwh => $prod['quantity']];
}
$preparebl = json_encode($arr);
echo $preparebl;
$offset += $limit;
}
}
}
}

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.

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;

Error in generating page number links using Codeigniter

I am creating a pagination using Codeigniter and my problem is I have an error in displaying the page number links in my URL.
example I go to page 2 my URL would be like this:
http://localhost/my_project/inbound/listing/1
if page 3
http://localhost/my_project/inbound/listing/2
Here's my controller
$config = array();
$config['base_url'] = base_url('inbound/listing');
$config['total_rows'] = $this->mod->countList();
$config['per_page'] = 1;
$config['uri_segment'] = 3;
//fd($config);
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
fp($page, 'pink'); //print out result
$order = ($this->input->get('order'))? $this->input->get('order'): '';
$sort = ($this->input->get('sort'))? $this->input->get('sort'): '';
// Query data
$data['data_list'] = $this->mod->listing($config['per_page'], $page); //where, limit, page, field, sort
fP($data['data_list']); //print out result
$data['pagination'] = $this->pagination->create_links();
Then my model for generating links:
function listing($limit, $start)
{
//DATE_FORMAT(`post_date_added`, "%m/%d/%Y %H:%i") as `proper_post_date_added`,
$this->db->select('*');
$this->db->from('inventory');
$this->db->limit($limit, $start);
$query = $this->db->get();
//$rows = $query->result_array();
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
Can you help me with this?
If you want to go to page number based on your url, modify your listing function to be like this:
function listing($limit, $start)
{
$offset_1 = $start - $limit;
$offset_2 = $offset_1 < 0 ? 0 : $offset_1;
//DATE_FORMAT(`post_date_added`, "%m/%d/%Y %H:%i") as `proper_post_date_added`,
$this->db->select('*');
$this->db->from('inventory');
$this->db->limit($limit, $offset_2);
$query = $this->db->get();
//$rows = $query->result_array();
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}

codeigniter pagination showing all query results in one page

hi every one i am trying to display mysql database records using codeigniter pagination..for that i written the following below codes..and when i run this it shows me all the results in one page while the page numbers are displayed right according to the given per_page limit..
Model:
function get_records($user_name, $limit, $start) {
$this->db->limit($limit, $start);
$this->db->select('GROUP_CONCAT(cid) AS cIDs');
$this->db->where('user_name', $user_name);
$this->db->group_by("company_user");
$this->db->from('company_records');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
function count_records($user_name) {
$this->db->select('GROUP_CONCAT(cid) AS cIDs');
$this->db->where('user_name', $user_name);
$this->db->group_by("company_user");
return $this->db->count_all('company_records');
}
Controller:
$this->load->model('Records', 'Records', TRUE);
$this->load->library('pagination');
$config['base_url'] = base_url() . 'records/index';
$config['total_rows'] = $this->Records->count_records($this->session->userdata('user'));
$config['per_page'] = 10;
$config["uri_segment"] = 4;
$config['use_page_numbers'] = TRUE;
$config['full_tag_open'] = '<div id="pagination">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
/* $start = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0; */
if ($this->uri->segment(4) > 0) {
$offset = ($this->uri->segment(4) + 0) * $config['per_page'] - $config['per_page'];
} else {
$offset = $this->uri->segment(4);
}
$data['recordsDetails'] = $this->Records->get_records($this->session->userdata('user'), $config["per_page"], $offset);
$data['pages'] = $this->pagination->create_links();
i have tried google search and stackoverflow.. but not yet found any solutions to this..may be i have issue with the query or i dont know..
please help me...
I used this code for pagination.
In the model
//Search for results
public function search($id, $table, $pageNumber) {
//Get the number of pages
$numOfPage = $this->findResults($id, $table, RETURN_NUM_OF_PAGES, $pageNumber);
if ($numOfPage < 1) {
return false; //If there are no search results return false
} else {
$row = array();
$res = $this->findResults($id, $table, RETURN_RESULTS, $pageNumber);
for ($j = 0; $j < $res->num_rows(); $j++) {
$row[$j] = $res->row($j);
}
return $row; //Return the results
}
}
// Find the results from DB and return number of pages/ results
function findResults($id, $table, $returnType, $pageNumber) {
$this->db->where('id', $id);
$this->db->order_by('reputation', 'desc'); //Order the users by reputation
$itemsPerPage = 4;
$startingItem = ($pageNumber - 1) * $itemsPerPage;
if ($returnType == RETURN_RESULTS) {
$res = $this->db->get($table, $itemsPerPage, $startingItem);
return $res; //Return the results
} else { //Return the number of pages
$res = $this->db->get($table);
$count = $res->num_rows(); //Get the total number of results
$numofPages = (int) ($count / $itemsPerPage);
if ($count % $itemsPerPage != 0)
$numofPages = $numofPages + 1; //If the number of items < $itemsPerPage there should be 1 page
return $numofPages; //Return the number of pages
}
}
So from the controller you have to call the function search($id, $table, $pageNumber).
Also the constants were defined in config/constants.php file as follows.
define('RETURN_NUM_OF_PAGES', 0);
define('RETURN_RESULTS', 1);

PHP pagination function

public function paging($limit,$numRows,$page){
$allPages = ceil($numRows / $limit);
$start = ($page - 1) * $limit;
$querystring = "";
foreach ($_GET as $key => $value) {
if ($key != "page") $paginHTML .= "$key=$value&";
}
$paginHTML = "";
$paginHTML .= "Pages: ";
for ($i = 1; $i <= $allPages; $i++) {
$paginHTML .= "<a " . ($i == $page ? "class=\"selected\" " : "");
$paginHTML .= "href=\"?{$querystring}page=$i";
$paginHTML .= "\">$i</a> ";
}
return $paginHTML;
}
This is my pagination function for MVC pattern implementation.But this function has not displayed next and prev links.
I need to return HTML variable for pagination with previous and next link to controller.
I passed these variable to this function from controller.
$limit,$numRows,$page
How can I get next and prev links to above function.
I have added some conditions in the loop itself.
Hope they work.
Try the following:
<?php
public function paging($limit,$numRows,$page){
$allPages = ceil($numRows / $limit);
$start = ($page - 1) * $limit;
$querystring = "";
foreach ($_GET as $key => $value) {
if ($key != "page") $paginHTML .= "$key=$value&";
}
$paginHTML = "";
$paginHTML .= "Pages: ";
for ($i = 1; $i <= $allPages; $i++) {
if ($i>1) {
$prev = $i-1;
$paginHTML .= 'Previous';
}
$paginHTML .= "<a " . ($i == $page ? "class=\"selected\" " : "");
$paginHTML .= "href=\"?{$querystring}page=$i";
$paginHTML .= "\">$i</a> ";
if ($i<$allPages) {
$next = $i+1;
$paginHTML .= 'Next';
}
}
return $paginHTML;
}
?>
I'm using this pagination class like bellow inside my controller
case '' :
$page = isset ( $_REQUEST ['page'] ) ? $_REQUEST ['page'] : 1;
$limit = 5;
$allStudent = $student->getAllStudents();
$numRows = count($allStudent);
$start = ($page - 1) * $limit;
$students = $student->getStudentsWithLimit($start,$limit);
$paginHTML = $pagin->paging($limit,$numRows,$page);
$view->render('view/allStudent.php', array('allStudent' => $students,'pagin' => $paginHTML ));
break;
Get record function in Model class
public function getStudentsWithLimit($start,$limit){
$stmt = $this->db->con->query("SELECT * FROM student LIMIT $start, $limit");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
This should page with next and previous links with a max of 5 on either side of current page.
Pass in a function if you want the link formatted differently.
I've only given this very limited testing, and its been pulled out of a class, so you could replace some hard coded values in here with parameters of references to $this
function get_paging_links($result_count, callable $format_function=null)
{
if(!$format_function){
$format_function = function($url,$page,$qs){
$qs['page'] = $page;
return $url.'?'.http_build_query($qs);
};
}
$per_page = 5;
$total_pages = ceil($result_count / $per_page);
$return = [];
parse_str($_SERVER['QUERY_STRING'],$qs);
$url = $_SERVER['REQUEST_URI'];
//Remove existing query_string.
if($pos = strpos($url,'?')){
$url = substr($url,0,$pos);
}
$current_page = isset($qs['page']) ? $qs['page'] : 1;
$previous = $current_page -1;
if ($previous) {
$return['previous'] = $format_function($url,$previous,$qs);
}
for($i = max(1,$current_page-5); $i <= min($total_pages,$current_page+5); $i++) {
$return["$i"] = $format_function($url,$i,$qs);
}
$next_page = $current_page + 1;
if ($next_page < $total_pages){
$return['next'] = $format_function($url,$next_page,$qs);
}
return $return;
}

Categories