counting the results in codeigniter - php

I want to count all the results in my table that has the same eventId in studentattendees table for every activity that I create. Here is a snippet of my two tables in my db. activity and studentattendees table.
studentattendees table:
activity table:
I want to know how I can make a model function that counts all the results where eventId in my studentattendees is equal to activityId in activity table. Also, how I would echo this in view. Here is a sample of my code in model, view, controller.
//view
public function getReportAttendees(){
$this->db->order_by('activity.activityId', 'DESC');
$query = $this->db->get('activity');
// date status
$resulting = $query->result_array();
foreach($resulting as $resultings){
$activity = $resultings['activityId'];
$this->db->join('activity', 'activity.activityId =
studentattendees.eventId');
$this->db->where('eventId',$activity);
$this->db->from('studentattendees');
$count = $this->db->count_all_results();
foreach($count as $counts){
array_push($countall, $count);
}
}
return $countall;
}
//view
<?php
if($attendee){
foreach($attendee as $attendees){
?>
<td><?php echo $attendees; ?></td>
<?php
}
}
?>
//controller
public function ReportGenerated(){
$data['attendee'] = $this->u->getReportAttendees();
$this->load->view('logmanagement/reportgenerated', $data);
}

//modal
public function getReportAttendees(){
$countall = array();
$this->db->order_by('activity.activityId', 'DESC');
$query = $this->db->get('activity');
$resulting = $query->result_array();
foreach($resulting as $resultings){
$activity = $resultings['activityId'];
$this->db->join('activity', 'activity.activityId = studentattendees.eventId');
$this->db->where('eventId',$activity);
$this->db->from('studentattendees');
$count = $this->db->count_all_results();
foreach($count as $counts){
array_push($countall, $count);
}
}
return $countall;
}
//view
<?php
if($attendee){
foreach($attendee as $attendees){
?>
<td><?php echo $attendees; ?></td>
<?php
}
}
?>
//controller
public function ReportGenerated(){
$data['attendee'] = $this->u->getReportAttendees();
$this->load->view('logmanagement/reportgenerated', $data);
}

Related

Database returning an empty Array() in PHP Codeigniter

I want to return and join 4 tables and produce a table for my view in a codeigniter application but it is returning Array().And to display the records I am using a foreach loop in my view but unable to display the records.
I have tried to change the query but then it does not return the desired results.
This is the Controller Function :-
public function student_list()
{
// get Student list
$this->data['student_list'] = $student_list = $this->Teachers_Model-
>getStudentList($_SESSION['user_id']);
//$this->data['student_list'] = $this->Teachers_Model-
>getStudents($_SESSION['user_id']);
print_r($this->data['student_list']);
// get courses
$this->data['courses'] = $courses = $this->Courses_Model-
>getCourses(null, $_SESSION['user_id']);
$this->render('student_list/index');
}
This is the Model :-
public function getStudentList($teacher_uid, $student_list_id = null){
$this->db->select('teachers_student.*, students.student_uid,
courses.course_id, users.username');
$this->db->from('teachers_student');
$this->db->join('students', 'students.student_uid =
teachers_student.student_uid');
$this->db->join('courses', 'courses.id = teachers_student.course_id');
$this->db->join('users', 'users.id = teachers_student.student_uid');
if(!is_null($student_list_id)):
$where = array(
'teachers_student.id' => $student_list_id,
'teachers_student.status' => 1,
);
$this->db->where($where);
$query = $this->db->get();
$result = $query->row_array();
else:
$where = array(
'teachers_student.teacher_uid' => $teacher_uid,
'teachers_student.status' => 1,
);
$this->db->where($where);
$query = $this->db->get();
$result = $query->result_array();
endif;
return $result;
}
And this is the view :-
<?php
foreach ($student_list as $key => $item) {
?>
<tr role="row" class="odd">
<td class="sorting_1"><?= $item->student_uid; ?></td>
<td class="sorting_1"><?= $item->username; ?></td>
<td class="sorting_1"><?= $item->course_id; ?></td>
</tr>
<?php } ?>

"Message : Undefined Variable:query " error on joining two tables codeigniter mysql php

I have two tables named 'addexpense' and 'addcategory' .
I have successfully joined each of the tables but on my view page the data are not viewing and an error message is passed on the screen. Please help.
This is my model
public function getExpenses(){
$this->db->select("addexpense.exp_date, addexpense.exp_amount, addexpense.exp_note, addexpense.exp_created, addcategory.category_name");
$this->db->from('addexpense');
$this->db->join('addcategory', 'addcategory.category_id = addexpense.category_id');
$query = $this->db->get();
return $query->result();
}
This is my Controller
public function join(){
$query = $this->base_model->getExpenses();
//$data['result'] = null;
if($query)
{
$data['query'] = $query;
}
$this->load->view('listexpense', $data);
}
This is my view code
<tr>
<td><strong>Date</strong></td>
<td><strong>Amount</strong></td>
<td><strong>Note</strong></td>
<td><strong>Created</strong></td>
<td><strong>Category Name</strong></td>
</tr>
<?php foreach($query as $expenses){?>
<tr>
<td><?=$expenses->exp_date;?></td>
<td><?=$expenses->exp_amount;?></td>
<td><?=$expenses->exp_note;?></td>
<td><?=$expenses->exp_created;?></td>
<td><?=$expenses->category_name;?></td>
</tr>
<?php }?>
set controller function this way
public function join(){
$data['query'] = $this->base_model->getExpenses();
$this->load->view('listexpense', $data);
}
Please can you check your data is going on view file or not by printing it at start of your view
<?php echo '<pre>';
print_r($query);
?>
It seems like you have not initialized model in controller.
In your controller you need to load model first before using its properties. Please check below for your controller method.
public function join() {
$this->load->model('base_model');
$query = $this->base_model->getExpenses();
$data = array();
if ($query) {
$data['query'] = $query;
}
$this->load->view('listexpense', $data);
}
Let me know still it not works.
Model change result() to result_array()
public function getExpenses(){
$this->db->select("addexpense.exp_date, addexpense.exp_amount, addexpense.exp_note, addexpense.exp_created, addcategory.category_name");
$this->db->from('addexpense');
$this->db->join('addcategory', 'addcategory.category_id = addexpense.category_id');
$query = $this->db->get();
return $query->result_array();
}
Controller try code below
public function join()
{
$results = $this->base_model->getExpenses();
$data['expenses'] = array();
foreach ($results as $result) {
$data['expenses'][] = array(
'exp_date' => $result['exp_date'],
'exp_amount' => $result['exp_amount'],
'exp_note' => $result['exp_note'],
'exp_created' => $result['exp_created'],
'category_name' => $result['category_name']
);
}
$this->load->view('listexpense', $data);
}
View make sure is the correct view
<table>
<thead>
</thead>
<tbody>
<?php foreach($expenses as $expense){?>
<tr>
<td><?php echo $expense['exp_date'];?></td>
<td><?php echo $expense['exp_amount'];?></td>
<td><?php echo $expense['exp_note'];?></td>
<td><?php echo $expense['exp_created'];?></td>
<td><?php echo $expense['category_name'];?></td>
</tr>
<?php }?>
</tbody>
</table>
Here is the code please check and update
Model
public function getExpenses(){
$this->db->select("addexpense.exp_date, addexpense.exp_amount, addexpense.exp_note, addexpense.exp_created, addcategory.category_name");
$this->db->from('addexpense');
$this->db->join('addcategory', 'addcategory.category_id = addexpense.category_id');
$query = $this->db->get();
$query_rows = $query->num_rows();
if($query_rows > 0){
return $query->result();
} else{
return 0;
}
}
For Controller
public function join(){
$this->load->model('base_model');
$query = $this->base_model->getExpenses();
//print_r($query);die();
$data['query'] = '';
if($query != 0){
$data['query'] = $query;
}
$this->load->view('listexpense', $data);
}
For View
<tr>
<td><strong>Date</strong></td>
<td><strong>Amount</strong></td>
<td><strong>Note</strong></td>
<td><strong>Created</strong></td>
<td><strong>Category Name</strong></td>
</tr>
<?php
if($query != ''){
foreach($query as $expenses){?>
<tr>
<td><?=$expenses->exp_date;?></td>
<td><?=$expenses->exp_amount;?></td>
<td><?=$expenses->exp_note;?></td>
<td><?=$expenses->exp_created;?></td>
<td><?=$expenses->category_name;?></td>
</tr>
<?php } }?>
remove the comment "//print_r($query);die();" and check that whether the model is sending the data or not and please update..

SQL Query with specific ID/row on Codeigniter

I need to print my data with specific ID by using SELECT * FROM query and I have problem with my query.
Example, i have table called tb_pasien , and it has 8 columns :
kode_pasien(as ID), nama_pasien, email_pasien, alamat_pasien, tanggal_lahir, umur, jenis_kelamin and no_telp.
So, when I want to print someone data it will only show her/his data not all data on my table.
This is my code :
Model
public function view_kartu()
{
$query = $this->db->query("SELECT * FROM tb_pasien where kode_pasien='$kode_pasien' LIMIT 1");
return $query;
}
Controller
public function cetakkartu() {
// Load all views as normal
$data['pasien'] = $this->a_model->view_kartu();
$this->load->view('cetak-kartu', $data);
// Get output html
$html = $this->output->get_output();
// Load library
$this->load->library('dompdf_gen');
// Convert to PDF
$this->dompdf->load_html($html);
$this->dompdf->render();
$this->dompdf->stream("cetak-kartu" . ".pdf", array ('Attachment' => 0));
}
View
<table border="1" width="100%">
<tr>
<th>Kode Pasien</th>
<th>Nama Pasien</th>
<th>Email Pasien</th>
<th>Alamat Pasien</th>
<th>Tanggal Lahir</th>
<th>Umur</th>
<th>JK</th>
<th>No. Telp</th>
</tr>
<?php
if( ! empty($pasien)){
foreach($pasien as $data){
echo "<tr>";
echo "<td>".$data->kode_pasien."</td>";
echo "<td>".$data->nama_pasien."</td>";
echo "<td>".$data->email_pasien."</td>";
echo "<td>".$data->alamat_pasien."</td>";
echo "<td>".$data->tanggal_lahir."</td>";
echo "<td>".$data->umur."</td>";
echo "<td>".$data->kode_jk."</td>";
echo "<td>".$data->no_telp."</td>";
echo "</tr>";
}
}
?>
</table>
But when i try to print it, it shows empty result. Can someone help me? Thankyou.
Need to the return result array or row but not query (as per your requirement of fetching data from array or array object)
Like this
return $query->result_array();
or
return $query->row();
Try changing your model function as below -
public function view_kartu($kode_paisen)
{
$query = $this->db->query("SELECT * FROM tb_pasien where kode_pasien='$kode_pasien' LIMIT 1");
return $query;
}
And then from your controller, call it as -
public function cetakkartu() {
//set a value for $kode_paisen
$kode_paisen = "XXX"; //set here whatever you like.
// Load all views as normal . See here we passing the variabke in the function.
$data['pasien'] = $this->a_model->view_kartu($kode_paisen);
// Rest of your function ...
}
As an example, i have a table "currency" in my site and this is how i fetch all the currencies mapped to a particular company in Code Igniter model.
function getCurrencyList($companyId)
{
$sql = "select currency_id from company_currency where company_id = $companyId";
$retVal = $this->db->query($sql);
if($this->db->affected_rows() == 0)
{
return null;
}
if($retVal && $this->db->affected_rows() > -1)
{
if($retVal->result_array())
{
foreach($retVal->result_array() as $row)
{
$arrCurrencyId[] = $row['currency_id'];
}
}
return $arrCurrencyId;
}
else
{
log_message('error', mysql_error()." ******* at function getActionList Role Model *********");
return null;
}
}
I hope this will help you
try this query:
$this->db->select('kode_pasien as ID, nama_pasien, email_pasien, alamat_pasien, tanggal_lahir, umur, jenis_kelamin, no_telp');
$this->db->from('tb_pasien');
$data= $this->db->get()->result_array();
echo "<pre>"; print_r($data);die;

Correct way to display my query

I have a query in my model that I need to print the data in my view
Model
function get_bank()
{
$query = $this->db->query("SELECT
(
12* (YEAR('account_add_date') - YEAR('start_date')) +
(MONTH('account_add_date') - MONTH('start_date'))
) AS differenceInMonth
->FROM ('bank')
WHERE mem_id = '".$this->session->userdata('id')."'");
return $query->result();
$data['account_age'] = $query->row_array();
}
and I am trying to print the output in my model, but its not working and I do not know where I have gone wrong. I am new to MVC and still getting used to it.
View
<h2>age of account</h2>
<?php
$age = $this->model('profiles_model' , $data );
print "<h2>$age</h2>";
?>
Controller
function index()
{
$data = array();
$this->load->model('user_profile/profiles_model');
$query = $this->profiles_model->get_bank();
if(!empty($query))
{
$data['records'] = $query;
}
$this->load->view('profile_view', $data);
}
Let's first write your code in proper convention.
Model
function get_bank() {
$mem_id = $this->session->userdata('id');
$query = $this->db
->select("12*(YEAR('account_add_date') - YEAR('start_date')) + (MONTH('account_add_date') - MONTH('start_date')) AS differenceInMonth")
->where('mem_id', $mem_id)
->get('bank');
return $query;
// $data['account_age'] = $query->row_array(); <-- Statement after return is useless.
}
Controller
function index() {
$data = array(
'records' => array()
);
$this->load->model('user_profile/profiles_model');
$bank = $this->profiles_model->get_bank();
if($bank->num_rows()){
$data['records'] = $bank->row_array();
}
$this->load->view('profile_view', $data);
}
View
Not sure what you are trying to do with the bank data but here's how you print the record
<p>Bank data</p>
<p><?=isset($records['differenceInMonth'])?$records['differenceInMonth']:"No record found"?></p>
You are not far away, do it this way:
Controller:
function index()
{
$this->load->model('user_profile/profiles_model');
$data = $this->profiles_model->get_bank();
$this->load->view('profile_view', $data);
}
Model:
function get_bank()
{
$query = $this->db->query("SELECT
(
12* (YEAR('account_add_date') - YEAR('start_date')) +
(MONTH('account_add_date') - MONTH('start_date'))
) AS differenceInMonth
->FROM ('bank')
WHERE mem_id = '".$this->session->userdata('id')."'");
return $query->result();
}
View:
<?php
foreach(differenceInMonth AS $age){
echo "<p>" . $age . "</p>";
}
When you load the view you are passing in $data with $data['records'] that has the data you are wanting to display.
Since that is how you pass the data into the view when you load it you will need to call it that way:
<?php
var_dump($records);
?>
You will also need to loop through the data as well assuming $records is an array of the query results or use var_dump instead of print just to verify the data is there.
Reading through these will help going forward:
https://codeigniter.com/user_guide/general/views.html
https://codeigniter.com/user_guide/general/models.html

DB query is not getting all records as defined

Model
$id = $this->session->userdata('id');
$q = $this->db->get_where('shipping_address', array('customer_id' => $id));
if ($q->num_rows == 0)
{
$data['id'] = 'You dont have a shipping address saved.';
} else {
foreach ($q->result() as $row)
{
$data['first'] = $row->firstname;
$data['last'] = $row->lastname;
}
}
return $data;
Controller
$this->load->model('Customer_accounts');
$customer = $this->Customer_accounts->get_customer_info();
$ship = $this->Customer_accounts->shipping_address();
$data = $ship + $customer;
$this->load->view('account_dashboard/personal_information', $data);
View
<?php foreach ($ship as $row) : ?>
<table class="fixCap" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><?php echo $row['firstname'] . $row['lastname']; ?></td>
</tr>
. . .
</tr>
</table>
<?php endforeach; ?>
Var_dump
Is only showing an array with 1 of the the table rows but it should be showing 2 rows which contain the defined customer_id
Problem
Unable to pass the all the db data to the foreach what am I doing wrong?
use:
$data = array_merge($ship, $customer); // they will merged as one array
or you can do it this way if u want them separated
$data = array();
$data['ship'] = $ship;
$data['customer'] = $customer;
//In the view
//ship
foreach($data['ship'] as $ship)
{
//Ship values
}
//customer
foreach($data['customer'] as $customer)
{
//Customer value
}
thx
You are not actually puling the result from database with your code.
try something like this
$ret = $q->get()->result();
foreach($ret as $row)
{
}
The problem was in my Model I replaced the above code with
Model
return $this->db->get_where('shipping_address', array('customer_id' => $id))->result();
And in my
View
#I echoed the vars as objects
$row->firstname

Categories