Codeigniter -> counting table numbers and show on the page - codeigniter

I wanna show number of rows of table on my website.
query is working on mysql page. it shows 1292.
Model
function count_bookmark()
{
$query = 'SELECT COUNT(*) FROM T_BOOKMARK_HISTORY';
$result = $this->db->query($query);
if($result->num_rows() <= 0)
return FALSE;
else{
return TRUE;
}
}
Controller
$data['count'] = $this->admin_model->count_bookmark();
View
<?=$count?>
This only show number 1.

You're simply returning TRUE or FALSE from your model. $count is then evaluated as 1. You need to return the actual count rather than just a boolean.
Also, to simplify things, you can use CodeIgniter's handy count_all method:
$count = $this->db->count_all('T_BOOKMARK_HISTORY');
return $count;
Then, in your view:
<?= $count ?>

Related

retrieve data from database in for loop

my controller is
function shiftstudentdetailsmultiple(){
$data['Show'] = $this->input->post('show[]');
$roll = $this->input->post('roll[]');
//echo sizeof($data1);
for($i=0;$i<sizeof($roll);$i++)
{
$data['results'] = $this->FetchData->getstudentsdetailscouseandmultiple($roll[$i]);
}
$this->load->view('registrar/shift_student_view', $data);
}
and model is
function getstudentsdetailscouseandmultiple($Uniq_Id){
$this->db->select("sprd.Uniq_Id, sprd.Name, sprd.Uni_Roll_No, cd.Course_Name, bd.Branch_Name, sprd.Year, sprd.Session, sprd.Section, sprd.Fee_Status, sprd.Curr_Status");
$this->db->where("sprd.Uniq_Id",$Uniq_Id);
$this->db->from("Students_Prim_Detals sprd");
$this->db->join('Course_Details cd', 'cd.Course_Id=sprd.Course_id');
$this->db->join('Branch_Details bd', 'bd.Branch_Id=sprd.Branch_id');
$query = $this->db->get();
if ($query->num_rows() > 0){
return $query->result();
}
else {
return false;
}
}
when showing in view the fetching data showing only one time.. but in my database i have more then 4 entry when i print_r
$data['results']=this->FetchData->getstudentsdetailscouseandmultiple($roll[$i]);
the data showing correct .. when load only showing one data..the last entry..
$this->load->view('registrar/shift_student_view', $data);
Each time you call...
$data['results'] = $this->FetchData->getstudentsdetailscouseandmultiple($roll[$i]);
you replace the value stored in $data['results'] with the new return. So only one return is sent to the view.
You will need to revise your controller along these lines.
$student_detail = array();
for($i=0;$i<sizeof($roll);$i++)
{
$student_detail[] = $this->FetchData->getstudentsdetailscouseandmultiple($roll[$i]);
}
$data['results'] = $student_detail;
Then in your view you will have to loop through $results to display each item in the array.
foreach($results as $detail){
echo "Name: ". $detail->name;
echo "Course: ". $detail->Course_Name;
//etc...
}

pagination doesn't work in codeigniter

I have successfully created pagination on some of the pages on the application on which I am working with, but I can't make it on this one:
I have 7 records in the database, and when
page is displayed all 7 records are displayed instead of 5, as I would like to be.
Sure enough, links for the paging are not displayed.
Here is my controller code:
public function displayAllFaqCategories()
{
//initializing & configuring paging
$currentUser = $this->isLoggedIn();
$this->load->model('faqCategoriesModel');
$this->db->order_by('sorder');
$limit = 5;
$offset = 3;
$offset = $this->uri->segment(3);
$this->db->limit(5, $offset);
$data['faq_categories'] = $this->faqCategoriesModel->selectCategoriesAndParents();
$totalresults = $this->db->get('faq_categories')->num_rows();
//initializing & configuring paging
$this->load->library('pagination');
$config['base_url'] = site_url('/backOfficeUsers/faqcategories');
$config['total_rows'] = $totalresults;
$config['per_page'] = 5;
$config['uri_segment'] = 3;
$this->pagination->initialize($config);
$errorMessage = '';
$data['main_content'] = 'faq/faqcategories';
$data['title'] = 'FAQ Categories';
$this->load->vars($data,$errorMessage);
$this->load->vars($currentUser);
$this->load->view('backOffice/template');
} // end of function displayAllFaqCategories
And here is my model function code:
public function selectCategoriesAndParents($selectWhat = array())
{
$data = array();
$query = $this->db->query("SELECT fq . * , COALESCE( fqp.$this->parent_name, '0' ) AS parentname
FROM $this->table_name AS fq
LEFT OUTER JOIN $this->table_name AS fqp ON fqp.catid = fq.parentid");
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$data[] = $row;
}
}
$query->free_result();
return $data;
} // end of function selectCategoriesAndParents
In the view, bellow of the table with the records I have the following code:
<?php echo $this->pagination->create_links();?>
Any help will be deeply appreciated.
Regards,Zoran
You've mixed two different things together I think. You're partially using the ActiveRecord class of CI, but then running the query yourself.
The simplest change would be:
// get all the rows
$data['faq_categories'] = $this->faqCategoriesModel->selectCategoriesAndParents();
// figure out the count of all of them
$totalresults = count($data['faq_categories']);
// only take some of the rows of the array, instead of keeping all of them and then showing all 7 of your records
$data['faq_categories'] = array_splice($data['faq_categories'], $offset, $limit);
Hopefully that should fix it!
To further explain what the original problem is, I think when you run this:
$totalresults = $this->db->get('faq_categories')->num_rows();
It takes the previous line $this->db->limit(5, $offset); into account, so it only returns 5 rows. Then, when you tell the pagination library that you only want to show 5 per page, the library thinks that it is actually showing all the results, so there is no need for pagination links!
Edit like this
$offset = $this->uri->segment(3) ? $this->uri->segment(3) : 0;

Codeigniter pagination with my own query

first be gentle im a begginer.
I have a problem with codeogniter pagination and im totally clules.
I watched a lot of tuts on the net and never got any aswer.
My problem is, im building a real-estate site, it has 2 types of estate, for sale and for rent.
My query looks like this
function for_sale()
{
$query = $this->db->query(" SELECT city, rand_id, price, image FROM estate WHERE type = 'for_sale' ");
if ($query->num_rows() > 0)
{
foreach ($query->result() as $f)
{
$for_sale[] = $f;
}
return $for_sale;
}
}
my controller
function index()
{
$this->load->view("header");
$this->load->model('estate_model');
$for_sale['result'] = $this->estate_model->for_sale();
$this->load->library('pagination');
$config['base_url'] = 'http://localhost/kpi/for_sale/index';
$config['total_rows'] = 22;
$config['per_page'] = 9;
$config['num_links'] = 19;
$this->pagination->initialize($config);
// $data['records'] = $this->db->get('ingatlan', $config['per_page'], $this->uri->segment(3));
$this->load->view("for_sale_view", $for_sale);
$this->load->view("footer");
}
and my view
foreach($results as $r) {
echo '<div class="grid_4">';
echo '<p class="title">Estate for sale</p>';
echo '<div class="thumbnail">
<div class="info">
<p class="bar">'.$r->city.'</p>
<p></p>
</div>
'.$r->image.'</div>';
echo '<div class="more">View details</div>';
echo '</div>';
}
So my problem is i cant figure this out how to use it with my query, i watched lots of tuts, that i need to load in the table library, and pass a data array like this
$data['records'] = $this->db->get('estate', $config['per_page'], $this->uri->segment(3));
anf give the per page this result `$this->db->get('estate')->num_rows(); but i would like this with my query, and not with a table.
So can someone hive me a hint?
Thank you
... i need to load in the table library, and pass a data array ...
how you display your data is totally up to you. the html-table class can help you with that, but it is not necessary to use it. your view should work just fine except for the fact that you want to iterate over $results which will be empty because you put your data into $for_sale['result'] (results != result).
in order for the pagination library to work with your query, you have to pass your query 2 parameters:
how many rows/records should be loaded from your db (= $config['per_page'])
how many rows/records should be skipped at the beginning (also known as 'offset', this value will be provided by the pagination library = $this->uri->segment(3))
So instead of:
$for_sale['result'] = $this->estate_model->for_sale();
Model:
function for_sale()
{
$query = $this->db->query(" SELECT city, rand_id, price, image FROM estate WHERE type = 'for_sale' ");
...
}
you should try:
$for_sale['result'] = $this->estate_model->for_sale($config['per_page'],$this->uri->segment(3));
Model:
function for_sale($per_page, $offset) {
$query = $this->db->query(" SELECT city, rand_id, price, image FROM estate WHERE type = 'for_sale' LIMIT $offset, $per_page");
...
return $query->result();
}
One last thing: the pagination library has to be initialized BEFORE you query the database.
And another last thing: $config['total_rows'] = 22; you will probably want to replace that with something like $this->estate_model->get_for_sale_total_rows()
Hope this helps.

How to display Serial Numbers in a table that has been created using table library in codeigniter?

I know how to create pagination and generate a table containing information from database in codeigniter, but I don't how to display the serial numbers for each row in the table. Example:
SL. Name Email
1. Srijon example#yahoo.com
2. Jake jake#yahoo.com
Would you please kindly show me how to do that? Thanks in advance
Here is the controller for how I create pagination and generate table (without serial numbers)
function index(){
$this->load->library('pagination');
$this->load->library('table');
$this->table->set_heading('Student ID','Student Name','Batch','Edit','Delete');
$config['base_url'] = 'http://localhost/coaching/index.php/student_list/index';
$config['total_rows'] = $this->db->get('student')->num_rows();
$config['per_page'] = 15;
$config['num_links'] = 20;
$config['full_tag_open'] = '<div id="pagination" align="center">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$data['tab'] = "Student List";
$this->load->model('mod_studentlist');
$data['records']= $this->mod_studentlist->student_list();
$data['main_content']='studentlist';
$this->load->view('includes/template',$data);
}
Here's my model
function student_list()
{
$config['per_page'] = 10;
$this->db->select('studentid, studentname, batch');
$this->db->order_by("studentid", "desc");
$rows = $this->db->get('student',$config['per_page'],$this->uri->segment(3))->result_array();
foreach ($rows as $count => $row)
{
$rows[$count]['studentname'] = anchor('student_list/get/'.$row['studentid'],$row['studentname']);
$rows[$count]['Edit'] = anchor('update_student/update/'.$row['studentid'],'Update');
$rows[$count]['Delete'] = anchor('report/'.$row['studentid'],'Delete');
}
return $rows;
}
Here's my view file
<?php echo $this->table->generate($records);?>
<?php echo $this->pagination->create_links();?>
<script type="text/javascript" charset="utf-8">
$('tr:odd').css('background','#EAEAEA');
</script>
You should create a variable inside your model function:
<?php
function student_list()
{
$config['per_page'] = 10;
$this->db->select('studentid, studentname, batch');
$this->db->order_by("studentid", "desc");
$rows = $this->db->get('student',$config['per_page'],$this->uri->segment(3))->result_array();
$sl = $this->uri->segment(3) + 1; // so that it begins from 1 not 0
foreach ($rows as $count => $row)
{
array_unshift($rows[$count], $sl.'.');
$sl = $sl + 1;
$rows[$count]['studentname'] = anchor('student_list/get/'.$row['studentid'],$row['studentname']);
$rows[$count]['Edit'] = anchor('update_student/update/'.$row['studentid'],'Update');
$rows[$count]['Delete'] = anchor('report/'.$row['studentid'],'Delete');
}
return $rows;
}
and modify your controller:
<?php
function index() {
$this->load->library('pagination');
$this->load->library('table');
$this->table->set_heading('SL.', 'Student ID','Student Name','Batch','Edit','Delete');
....
Codeigniter has a great Table library to display data in html table format. Adding a Serial No is sometime required to a table, but Row num is not easily provided by MySQL hence while using Table library this function is added to do the job.
Here goes the code:
/**
* Set the serial no
*
* Add serial no to left of table
*
* #access public
* #param mixed
* #return mixed
*/
function add_sr_no(&$arr)
{ if (!is_array($arr)) return $arr;
$i=1;
foreach ($arr as &$values) {
if (!is_array($values))
break;
else
array_unshift($values, $i++);
}
return $arr;
}
Just add these lines to table.php in library.
Usage:
$rows = $query->result_array();
$this->table->add_sr_no($rows);
Don't forget to add first column 'Sr No' in set_heading.
Read the post here.
Hope this helps.
Have you thought about doing this on the client? the javascript library datatables is brilliant. it can handle the sorting for you at the user side, and can be made to dynamically retrieve information using ajax, so load times are fast on large tables. for under < 100 rows or so there probably isn't a need though. i have it sorting/filtering tables with >100 000 rows with no problems at all (using ajax)
unless the serial numbers have semantic meaning don't show them to the client. it just more stuff for them to filter. if they are required for your code, but not for the user to see, just hide them away in a data attribute or something.

CI pagination, POST method not working

Okay, I am pretty new in CI and I am stuck on pagination. I am performing this pagination on a record set that is result of a query. Now everything seems to be working fine. But there's some problem probably with the link. I am displaying 10 results per page. Now if the results are less than 10 then it's fine. Or If I pull up the entire records in the table it works fine. But in case the result is more than 10 rows, then the first 10 is perfectly displayed, and when I click on the pagination link to get to the next page the next page displays the rest of the results from the query as well as, other records in the table. ??? I am confused.. Any help??
Here's the model code I am using ....
function getTeesLike($field,$param)
{
$this->db->like($field,$param);
$this->db->limit(10, $this->uri->segment(3));
$query=$this->db->get('shirt');
if($query->num_rows()>0){
return $query->result_array();
}
}
function getNumTeesfromQ($field,$param)
{
$this->db->like($field,$param);
$query=$this->db->get('shirt');
return $query->num_rows();
}
And here's the controller code ....
$KW=$this->input->post('searchstr');
$this->load->library('pagination');
$config['base_url']='http://localhost/cit/index.php/tees/show/';
$config['total_rows']=$this->T->getNumTeesfromQ('Title',$KW);
$config['per_page']='10';
$this->pagination->initialize($config);
$data['tees']=$this->T->getTeesLike('Title',$KW);
$data['title']='Displaying Tees data';
$data['header']='Tees List';
$data['links']=$this->pagination->create_links();
$this->load->view('tee_res', $data);
What am I doing wrong here ???? Pls help ...
I guess the problem is with the $KW=$this->input->post('searchstr'); ..
Because if I hard code a value for $KW it works fine. May be I should use POST differently ..but how do I pass the value from the form without POSTING it , its CI so not GET ... ??????
In Controller
<?php
$KW=$this->input->post('searchstr');
$this->load->library('pagination');
$count = $this->model_name->getNumTeesfromQ($KW);//Count
$config['base_url']= base_url().'index.php/tees/show/';
$config['total_rows']= $count;
$config['per_page']='10';
$config['uri_segment'] = 4;
$limit = $config['per_page'];
$this->pagination->initialize($config);
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$data['links'] = $this->pagination->create_links();
$data['tees']=$this->model_name->getTeesLike($KW,$limit,$page);
$data['title']='Displaying Tees data';
$data['header']='Tees List';
$this->load->view('tee_res', $data);
In Model
public function getNumTeesfromQ($KW)
{
$query = $this->db->query("SELECT * FROM title WHERE table_field='$KW'");
$result = $query->result_array();
$count = count($result);
return $count;
}
public function getTeesLike($KW,$limit,$page)
{
$query = $this->db->query("SELECT * FROM title WHERE table_field='$KW' LIMIT $page, $limit");
$result = $query->result_array();
return $result;
}
in view
echo all data using foreach
then at bottom of page use <?php echo $links; ?>this will show your Pagination

Resources