How to print count in view using Codeigniter - php

I am new to Codeigniter and I am facing an issue with printing count in admin dashboard.
The following code is what I am trying now. Please tell me what I am doing wrong.
my model
function todayorder(){
$sql=$this->db->query("select count(*) as count from orders where order_date_time >= CURDATE()");
return $sql->row();
}
controller
public function orderlist(){
if(isset($_SESSION['admin_id'])){
$data["row"]=$this->picShuModel->orderlist();
$this->load->view('admin/index',$data);
$query = $this->picShuModel->todayorder();
$data['count'] = $query->count;
$this->load->view('admin/index',$data);
}else{
$this->load->view('admin/login');
}
}
and my view* in the dashboard
<?php foreach($data as $count){echo $count;}?>

In your view you can directly use $count as a variable.
Change
<?php foreach($data as $count){echo $count;}?>
To
echo $count;
Update
public function orderlist(){
if(isset($_SESSION['admin_id'])){
$data["row"]=$this->picShuModel->orderlist();
$query = $this->picShuModel->todayorder();
$data['count'] = $query->count;
$this->load->view('admin/index',$data);
}else{
$this->load->view('admin/login');
}
}

This below line assigns count to array variable
$data['count'] = $query->count;
To access count in view page
<?php
echo $count ; // you have use element of data rather $data. this print the count value
?>
In controller you are loading view page twice, load view page once

Related

i want to display value from database in codeigniter but i am getting errror

I want to display a value in view in CodeIgniter but I am getting several errors like trying to get the property on non-object. I think my code is correct but I am getting errors. Below is my code.
controller:
public function trainer($id)
{
$user_record = $this->db->query("select * from usr_data where usr_id=$id")->result();
$data['title'] = 'trainer Dashboard';
$data['user_record'] = null;
$data['active_courses'] = [];
$data['inprogress'] = [];
if(count($user_record)) {
$user_record = $user_record[0];
$data['title'] = ucwords($user_record->firstname).' Dashboard';
$data['user_record'] = $user_record;
$active_courses = $this->base_model->getTrainercourseAll($id);
$data['active_courses'] = $active_courses;
$inprogress = $this->base_model->getstaffinprogress($id);
$data['inprogress'] = $inprogress;
}
$this->load->view('trainer-dashboard', $data);
}
model:
public function getstaffinprogress($user_id) {
$result=$this->executeSelectQuery("select AVG(m.percentage) from object_data o, ut_lp_marks m where o.obj_id=m.obj_id and o.type='crs' and m.status=1 ");
return $result;
}
view:
<h3>Avg inprogress:<?php echo "<span style='color:#ff00ff;font-family:verdana;'>".$inprogress->percentage."</span>";?></h3>
I want to display the column percentage which is coming from database.above code is in the controller, model and view.i thought my controller code is wrong.
Anyone help me to get rid of this error. I want to display a value in view in CodeIgniter but I am getting several errors like trying to get the property on non-object. I think my code is correct but I am getting errors. Below is my code.
Try this in your view file,
if(isset($inprogress)){
echo $inprogress->percentage;
}
Then your code look like this,
<h3>Avg inprogress:<?php if(isset($inprogress)){ echo "<span style='color:#ff00ff;font-family:verdana;'>".$inprogress->percentage."</span>";}?></h3>
Then call the controller function. I think inprogress is not set at the first time.
If it doesn't work, try to var_dump($inprogress) in controller and check value and type.
And try this code in your model. Query also seems not correct
public function getstaffinprogress($user_id) {
$this->db->select_avg('ut_lp_marks.percentage');
$this->db->where('ut_lp_marks.obj_id', $user_id);
$this->db->where('object_data.type', 'crs');
$this->db->where('ut_lp_marks.status', 1);
$this->db->join('object_data', 'object_data.obj_id = ut_lp_marks.obj_id');
$query = $this->db->get('ut_lp_marks');
return $query->result_array();
}
I assume that your db is ut_lp_marks. Then var_dump array and check data is correct first. Then access array element.
public function getstaffinprogress($user_id) {
$result = array();
$query=$this->db->query("select AVG(m.percentage) from object_data o, ut_lp_marks m where o.obj_id=m.obj_id and o.type='crs' and m.status=1 ");
foreach($query->result() as $row){
$result = $row;
}
return $result;
}
Also check $inprogress->percentage exists before print in view.

Fetch data from database in codeigniter

I have 2 cases where i am fetching the entire data and total number of rows of a same table in codeigniter, I wish to know that is there a way through which i can fetch total number of rows, entire data and 3 latest inserted records from the same table through one code
Controller code for both cases is as given below (although i am applying it for each case seperately with different parameters)
public function dashboard()
{
$data['instant_req'] = $this->admin_model->getreq();
$this->load->view('admin/dashboard',$data);
}
1) to fetch the entire data from a table in codeigniter
Model Code
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
return $query->result();
}
View Code
foreach ($instant_req as $perreq)
{
echo $perreq->fullname;
echo "<br>";
}
2) to fetch number of rows from a table in codeigniter
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
return $query->num_rows();
}
View Code
echo $instant_req;
You can make only one function that gives you the all data at once total number of rows, entire data and 3 latest inserted records
for example in the model
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
$result=$query->result();
$num_rows=$query->num_rows();
$last_three_record=array_slice($result,-3,3,true);
return array("all_data"=>$result,"num_rows"=>$num_rows,"last_three"=>$last_three_record);
}
in controller dashboard function
public function dashboard()
{
$result = $this->admin_model->getreq();
$this->load->view('admin/dashboard',$result);
}
in view
foreach ($all_data as $perreq)
{
echo $perreq->fullname;
echo "<br>";
}
//latest three record
foreach ($last_three as $perreq)
{
echo $perreq->fullname;
echo "<br>";
}
//total count
echo $num_rows;
Raw query may work here.
$resultSet = $this->db->query("select * from table_name");
$queryCount = count($resultSet );
Try this logic :
Model code :
public function getreq()
{
$this->db->where('status','pending');
$this->db->order_by('id', 'DESC'); //actual field name of id
$query=$this->db->get('instanthire');
return $query->result();
}
Controller Code :
public function dashboard()
{
$data['instant_req'] = $this->admin_model->getreq();
$data['total_record'] = count($data['instant_req']);
$this->load->view('admin/dashboard',$data);
}
View Code:
$i=0;
foreach ($instant_req as $perreq)
{
if($i<3){
echo $perreq->fullname;
echo "<br>";
}
$i++;
}
Echo 'Total record : '.$total_record;
Function
function getData($limit = 0){
//Create empty array
$data = [];
//Where clause
$this->db->where('status','pending');
//Order Data based on latest ID
$this->db->order_by('id', 'DESC');
if($limit != 0){
$this->db->limit($limit);
}
//Get the Data
$query = $this->db->get('instanthire');
$data['count'] = $query->num_rows();
$data['result'] = $query->result();
return $data;
}
Calls
//Last 3 Inserted
$data = getData(3);
//All Data
$data = getData();
CodeIgniter Database Documentation
Here is a simple solution that I can first think of but if you want me to maybe improve I can.
Just stick with your first code(Model) and in the view count how many items are iterated through.
$count = 0;
foreach ($instant_req as $perreq)
{
echo $perreq->fullname;
echo "<br>";
$count++;
}
echo $count;
Am I still missing something? just let me know
EDIT:
This is another solution, return an array
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
$data['results'] = $query->result();
$data['count'] = $query->num_rows();
return $data
}
I'm not very confident and haven't really tried this but on top of my head I think it can work.
Model:
public function getreq()
{
$res = $this->db->order_by("<place column primary id>","desc")->get_where('instanthire',['status'=> 'pending']);
$latest_3 = [];
if(count($res)){
$i=1;
foreach($res as $r){
$latest_3[]=$r;
if($i == 3)
break;
$i++;
}
}
$arr = [
'latest_3' => $latest_3,
'count' => count($res),
'total_result' => $res,
];
return $arr;
}

Codeigniter php MVC

I have a table called 'News' with three columns: 'id', 'title' and 'details'
I have a function ('get_entry') inside a codeigniter model class (called 'News_model')
function get_entry()
{
$this->load->database();
return $this->db->select('id,title,details')->from ('news');
$data['newsarray'] = $this->db->row_array();
return $data['newsarray'];
}
I am connecting to the db so that is not the problem.I want to return an iterable array from get_entry() by calling the function from a controller file with the followlwing code. I want to push it into another array (called '$data['theNews']') using the code below.
foreach ($this->News_model->get_entry() as $key => $value){
array_push($data['theNews'],$value->title);
}
I have been using the code on this (https://www.codeigniter.com/user_guide/general/models.html) as a template (in particular the function 'get_last_ten_entries()' but I think I am close with the code I posted above. I would appreciate any help.
About your code:
You have two 'return' in your get_entry function:
function get_entry()
{
$this->load->database();
// First
return $this->db->select('id,title,details')->from ('news');
$data['newsarray'] = $this->db->row_array();
// Second
return $data['newsarray'];
}
Change it to:
function get_entry()
{
$this->load->database();
$query = $this->db->select('id,title,details')->from('news');
$data['newsarray'] = $query->row_array();
return $data['newsarray'];
}
It should work now.
Some advices:
Don't use Codeigniter 2 anymore. Version 3 is alive.
If you plan to return whole table columns, i suggest you to use the following code for the query:
$query = $this->db->get('news', 1, 20);
Where 1, 20 is the limit.
Now you can get the result:
return $query->result();
A simple example:
function get_entry()
{
$this->load->database();
$query = $this->db->get('news', 1, 20);
return $query->result();
}
This method returns the query result as an array of objects that you can print like so in your controller:
$news_array = $this->News_model->get_entry();
foreach ($news_array as $news)
{
echo $news->id;
}
Look at CI 3 Query Builder query builder for more examples.
One more suggestion, just autoload the database library in application/config/autoload.php if you need it globally.
Changing the code to this in the function worked:
function get_entry()
{
$this->load->database();
$query = $this->db->get('news');
//return $query->result();
foreach ($query->result() as $row)
{
echo "</br>";
echo $row->id;
echo "</br>";
echo $row->title;
echo "</br>";
echo $row->details;
echo "</br>";
}
}
Calling the function like so prints it out:
$news_array = $this->News_model->get_entry();

How to pass data from an customized helper to a view with codeigniter

I have created an helper class to show values coming from a database.
Helper
if (!function_exists('items')){
function show_items($item) {
$ci = get_instance();
$sql = " SELECT * FROM table WHERE items = '$item'";
$result = $ci->db->query($sql);
return $result->row();
}
}
In the view I use the function like this:
echo show_items($item)->main_image);
The echo above shows obviously only the first row of main_image.
My goal is to show all the rows of the selected $item.
If I change the helper like this
$sql = " SELECT * FROM table WHERE items = '$item'";
$result = $ci->db->query($sql);
return $result->result();// first option
return $result->result_array();//second option
}
}
how can I loop the result in the view using for istance a foreach?
your helper code with
$query->result_array():
//this is your view code
<?php $result = show_items($item); ?>// call helper
// DATA RECALL FROM THE HELPER
<?php foreach($result as $data): ?>
<?php echo $data['main_image']; ?>
<?php endforeach; ?>

Displaying data from database using Codeigniter

I am trying to get data from a database and display it using a model, controller, and view.
Here is my model
public function waitlist_view() {
$data = array();
$this->load->database();
$this->db->select('*');
$this->db->from('waitlist');
$query = $this->db->get();
return $query->row();
}
Here is my controller
public function waitlist() {
$data['title']="parents_viewlist";
//redirect if not logged in
if(($this->session->userdata('logged_in')!= 1) && ($this->session->userdata('type')!='parent')) {
redirect('login/index');
}
$this->load->model('parents_model');
$data['row'] = $this->parents_model->waitlist_view();
$this->load->view('templates/cpsheader', $data);
$this->load->view('templates/cpsmenu');
$this->load->view('parents/parents_viewlist', $data);
$this->load->view('templates/cpsfooter');
}
Here is my view
<div>
<?php echo $row->waitlist_id; ?>
<?php echo $row->ay_code; ?>
<?php echo $row->school_id; ?>
<?php echo $row->waitlist_status; ?>
</div>
It doesnt display anything on the page when I pull it up. Any help would be appreciated!
in your model use result() to get data :
public function waitlist_view() {
$this->load->database();
$query = $this->db->get('waitlist')->result();
return $query;
}
in your controller :
$this->load->model('parents_model');
$data['row'] = $this->parents_model->waitlist_view();
$this->load->view('templates/cpsheader', $data);
$this->load->view('templates/cpsmenu');
$this->load->view('parents/parents_viewlist', $data);
$this->load->view('templates/cpsfooter');
Now use loop on $row in your view to print data.
In your controller print the data returned from db as:
echo "<pre>";print_r($data);echo "</pre>";exit;
add this line just after $data['row'] = $this->parents_model->waitlist_view();
Let us know what result are you getting.

Categories