Using aggregate function SUM() in CodeIgniter - mysql

Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class transaction extends CI_Model{
public function mytransaction(){
$this->load->database();
$query = $this->db->get('transaction');
return $query->result();
}
public function mySum(){
$this->db->select("SUM(total) AS MySum");
$this->db->from("transaction");
return $query1->row();
}
}
Controller
class Invoice extends CI_Controller{
public function index(){
$this->load->Model('transaction');
$data1['query'] = $this->transaction->mytransaction();
$this->load->view('transactionview', $data1);
}
}
View
<table width="600px" border="1px" style="margin:40px 300px;">
<tr>
<td>Sno.</td>
<td>Product Code</td>
<td>Name</td>
<td>Quantity</td>
<td>Rate</td>
<td>Total</td>
</tr>
<?php foreach($query as $row){?>
<tr>
<td><?php echo $row->transaction_id;?></td>
<td><?php echo $row->code;?></td>
<td><?php echo $row->name;?></td>
<td><?php echo $row->quantity;?></td>
<td><?php echo $row->rate;?></td>
<td><?php echo $row->total;?></td>
</tr>
<?php }?>
<tr>
<td colspan=4>Subtotal</td>
<td colspan=2>?</td>
</tr>
<tr>
<td colspan=4>Grand Total</td>
<td colspan=2>?</td>
</tr>
</table>
I am trying to use aggregate function with Codeigniter. For this I want to write a query which sums all total column of the table so that I can echo it to the Grand total field of the table.For this how can I pass the sum value from my model to view so that I can echo sum value in my table?

model function:-
public function mySum(){
$this->db->select("SUM(total) AS MySum");
$this->db->from("transaction");
$query1 = $this->db->get();
if($query1->num_rows() > 0)
{
$res = $query1->row_array();
return $res['MySum'];
}
return 0.00;
}
call your model function in your controller:-
// set grand total here
$data1['g_total'] = $this->transaction->mySum();
get in view as:-
<tr>
<td colspan=4>Grand Total</td>
<td colspan=2><?php echo $g_total;?></td>
</tr>

Related

how to display ticket where i want data from booking page in codeigniter

In the previous page i filled payment details and submited and it shows train booked and i want to print ticket but im not getting data of the present booking .i tried to get data with booking_id but its not retrieving data.i can get retrieve data with passenger_id but it is not unique bcz one user can book multiple trains so it shows first entry in the database if there are multiple entries by one passenger .but im not being to get data with booking_id.help me!!!!!!
model
public function viewtrain($booking_id=null)
{
if($booking_id)
{
$this->db->select('*');
$this->db->from('booked');
$this->db->where('booking_id=?');
$alltrains=$this->db->get();
return $alltrains->result();
}
}
view
<table class="table table-type " style="text-align:center">
<thead>
<tr>
<th scope="col">Train ID</th>
<th scope="col">Origin</th>
<th scope="col">Destination</th>
<th scope="col">Date</th>
<th scope="col">Arrival Time</th>
<th scope="col">Departure Time</th>
<th scope="col">Class</th>
<th scope="col">Price</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<?php if(count($alltrains)):?>
<?php foreach($alltrains as $alltrain): ?>
<tr class="table-type">
<td><?php echo $alltrain->booking_id; ?></td>
<td><?php echo $alltrain->origin; ?></td>
<td><?php echo $alltrain->destination; ?></td>
<td><?php echo $alltrain->date; ?></td>
<td><?php echo $alltrain->arrivaltime; ?></td>
<td><?php echo $alltrain->departuretime; ?></td>
<td><?php echo $alltrain->class; ?></td>
<td><?php echo $alltrain->price; ?></td>
<td>
<?php echo anchor("admin/edittrain/{$alltrain->train_id}",'Edit',['class'=>'btn btn-outline-primary','style'=>'font-size:15px;height:20px;width:40%;padding-top :0px;']); ?>
<?php echo anchor("admin/deletetrain/{$alltrain->train_id}",'Delete',['class'=>'btn btn-outline-danger','style'=>'font-size:15px;height:20px;width:50%;padding-top :0px;']); ?>
</td>
</tr>
<?php endforeach;?>
<?php else:?>
<tr>
<td></td>
<td></td>
<td></td>
<td><h4>NO Trains Available!!</h4></td>
<td></td>
<td></td>
<td></td>
</tr>
<?php endif;?>
</tbody>
</table>
Controller
public function ticket($booking_id=null)
{
$this->load->model('user_model');
$alltrains=$this->user_model->viewtrain($booking_id);
$this->load->view('ticket',['alltrains'=>$alltrains]);
}
The data is not being retrieved because the format is wrong in your model, I've written the correct format below, see if this helps you.
Model
if($booking_id)
{
$this->db->select('*');
$this->db->from('booked');
$this->db->where('booking_id', $booking_id);
$alltrains=$this->db->get();
return $alltrains->result();
}

Distinct with join in codeigniter mysql

How can I use Distinct with join in CodeIgniter, I'm trying to fetch customer's name and registered category, but my problem is whiles fetching the data I'm getting data in repetation because of sub-category, I've used distinct but then I'm getting Ambiguous field error, how can I solve this problem.
My View
<table class="table table-hover example1">
<thead>
<tr>
<th>SNo.</th>
<th>Business Name</th>
<th>Category Name</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<?php $i=0;
foreach($value as $row){ ?>
<tr>
<td><?php echo ++$i;?></td>
<td><?php echo $row->Bussiness_Name;?></td>
<td><?php echo $row->Category_Name;?></td>
<td onClick="RestoreVendor(<?php echo $row->Business_Id; ?>,<?php echo $row->Trash;?>,'<?php echo $row->Bussiness_Name;?>')" class="btn btn-primary">Remove</td>
</tr>
<?php }?>
</tbody>
</table>
My Controller:
public function removecategory()
{
$this->load->model('VendorModel');
$data = $this->VendorModel->remove_category();
$this->load->view('admin/remove_cat', array('value'=>$data));
}
My Model
public function remove_category()
{
$this->db->select('*');
$this->db->distinct('Category_Id');
$this->db->from('business_mapping');
$this->db->join('business_profile_details', 'business_profile_details.Business_Id = business_mapping.Business_Id');
$this->db->join('category_master', 'category_master.Category_Id = business_mapping.Category_Id');
$query = $this->db->get();
return $query->result();
}
result image
You can use below mentioned query.
$query = $this->db->group_by('category_master.Category_Id,business_profile_details.Business_Id');
Please try above, It will help you.
you can use
$this->db->distinct();
Some times distinct not works then you can use
$this->db->group_by('business_mapping.unique_coloumn_Name');

Zend form input box aligning

This is my HTML view:
<tr class="header">
<th>CLASS</th>
<th>NAME</th>
<th>Actions</th>
</tr>
<?php
foreach($this->documents as $row): ?>
<tr>
<td><?php echo $row['CLASS'];?></td>
<td><?php echo $row['NAME'];?></td>
href="/admin/documents/delete?ID=<?php echo $row['ID'];?>">
delete</a>
</td>
</tr>
<?php endforeach; ?>
</table>
</div>
This is my view Form:
public function init()
{
$CLASS = new Zend_Form_Element_Text('CLASS');
$CLASS->setLabel('CLASS')
->setRequired(true);
$NAME = new Zend_Form_Element_Text('NAME');
$NAME->setLabel('NAME')
->setRequired(true);
$submit = new Zend_Form_Element_Submit('Submit');
$submit->setAttrib('ID', 'submitbutton');
$this->addElements(array($CLASS, $NAME,$submit));
}
I have zend form, having two inputs CLASS and NAME.
How to display CLASS and required input text box column in the same line?
This is my output image:
And same thing, how to put submit and Reset button in the same line?

codeigniter- 3 pagination loading all data on all page

my models
function get_all_events($limit = null, $offset = null) {
if ($limit) {
$this->db->limit($limit, $offset);
}
$this->db->order_by('events.added_on', 'desc');
return $this->db->get('events');
}
my controller
public function manage_events() {
$this->securepage();
$data['events'] = $this->events_model->get_all_events();
$this->load->library('pagination');
$config['base_url'] = site_url('events/manage-events');
$config['total_rows'] = $this->events_model->get_all_events()->num_rows();
$config['per_page'] = 2;
$config['uri_segment'] = 3;
$this->pagination->initialize($config);
$data = array(
'news_title' => 'Manage events | kanchan news.com' ,
'Keywords' => 'manage',
'url' =>'' ,
'content'=> $this->load->view('events/manage', $data, true)
);
$this->load->view('kanchan', $data);
}
My view
<div class="container">
<ol class="breadcrumb">
<li class="active"><?php echo $this->session->userdata('full_name');?></li>
<li class="active">Manage Events</li>
</ol>
<h1>Manage Events here.</h1>
<?php echo $this->session->flashdata('msg'); ?>
<div>
<?php if ($events->num_rows()): ?>
<table class="table table-condensed">
<thead>
<tr>
<th>SN</th>
<th>Add Title</th>
<th>expire date</th>
<th>Added on</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($events->result() as $u): ?>
<tr>
<td><?php echo $u->id; ?></td>
<td><?php echo $u->heading = word_limiter($u->heading,10); ?></td>
<td><?php echo $u->venue; ?></td>
<td><?php echo date('Y-m-d | h:i:a', $u->added_on); ?></td>
<td>
<span class="glyphicon glyphicon-trash"></span>
&nbsp &nbsp <span class="glyphicon glyphicon-edit"></span>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p>No any Events
<hr>
Add New Events
</p>
<?php endif; ?>
</div>
<?php echo $this->pagination->create_links();?>
</div>
It creates pagination <1 2 but it loads all result on page 1 and also same result on page 2 and I had tried many ideas but it does not work.
I'm using codeigniter 3 and mysql .
It happen because you are getting all records at every page.You did not pass $limit and $offset. at your function.
$data['events'] = $this->events_model->get_all_events();//getting all records every time.
Try to write your manage_event function like this way
public function manage_events($page_num=1)
{
$this->securepage();
$data['events'] = $this->events_model->get_all_events(2,($page_num-1)*2);
///keep your rest code here
//remember this 2 is from your config because you wanted view 2 record per page.You can replace it with your varible.
Note
$config['base_url'] = site_url('events/manage-events');
This should be
$config['base_url'] = site_url('events/manage_events');//underscore not hypen

PHP Array doesn't show all the data from database

I have a very basic and simple script that should display records from my database. The problem: it doesn't show all the records. I've tried it even with the most simple mysql
($sql="SELECT * FROM $tbl_name";) but still some records are missing (mostly the first of the list that isn't shown).
So here is my code (it's all on 1 page):
<?php
$host="localhost";
$username="***";
$password="***";
$db_name="***";
$tbl_name="***";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name WHERE rowNameOne >= 0.01 AND rowNameTwo='2013'";
if ($_GET['sort'] == 'one')
{
$sql .= " ORDER BY one ASC";
}
elseif ($_GET['sort'] == 'two')
{
$sql .= " ORDER BY two ASC";
}
elseif ($_GET['sort'] == 'three')
{
$sql .= " ORDER BY three ASC";
}
elseif($_GET['sort'] == 'four')
{
$sql .= " ORDER BY four ASC";
}
elseif($_GET['sort'] == 'five')
{
$sql .= " ORDER BY five ASC";
}
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<body onload="parent.alertsize(document.body.scrollHeight);">
<br />
<table cellspacing="0" cellpadding="0" align="center">
<tr>
<td valign="top" colspan="5">
<font>Titel</font>
</td>
<tr>
<td>Titel one</td>
<td>Titel two</td>
<td>Titel three</td>
<td>Titel four</td>
<td>Titel five</td>
</tr>
<tr>
<td colspan="5" class="noBorder">
<?php
while($rows=mysql_fetch_array($result)){
?>
<a href="pageName.php?id=<? echo $rows['id']; ?>" >
<table width="100%">
<tr>
<td><? echo $rows['rowNameOne']; ?></td>
<td><? echo $rows['rowNameTwo']; ?></td>
<td><? echo $rows['rowNameThree']; ?></td>
<td><? echo $rows['rowNameFour']; ?></td>
<td><? echo $rows['rowNameFive']; ?></td>
</tr>
</table>
<input name="id" type="hidden" id="id" value="<? echo $rows['id']; ?>">
<?php
}
?>
</a>
</td>
</tr>
</table>
It's a very basic code, easy as can be I would say, but still it's missing records, not displaying everything that's in the database. What am I doing wrong?
Thanks for the help!
Before you start the loop, you do this:
$rows=mysql_fetch_array($result);
Then the loop condition is:
while($rows=mysql_fetch_array($result)){
So the first result is never shown. I would advice to remove the first statement, since you're not using its results between that statement and the loop.
On a related note, please consider moving to PDO or mysqli.