I have my little project coding with Codeigniter, I am just stuck in querying the total count of specific column to show in a View. Here are some pieces of my code where I get stuck:
Model:
function get_dailyprob()
{
$date = date('d-m-Y');
$q1 = $this->db->select('client')->like('created_at', $date)->group_by('client')->get('histprob')->result();
$q2 = $this->db->like('created_at', $date)->count_all_results('histprob'); //HERE I HAVE NO IDEA HOW TO GET A TOTAL COUNT OF EACH ROWS THAT ALREADY GROUPED BY COLUMN client
return array('dp_client' => $q1, 'dp_count' => $q2);
}
Controller:
$data['dailyprobs'] = $this->skejuler_m->get_dailyprob();
View:
<table class="table table-hover">
<?php if ($dailyprobs['dp_count'] > 0) {
foreach ($dailyprobs['dp_client'] as $dpc): ?>
<tr>
<td><?php echo $dpc->client; ?></td>
<td><span style="font-size:16px" class="badge bg-red"><?php echo $dailyprobs['dp_count']; ?></span></td>
</tr>
<?php endforeach; ?>
<tr><td><?php } else { echo 'No Issues!'; } ?></td></tr>
</table>
$dpc->client results some rows and each row has different count (filtered by query in Model)
$dailyprobs['dp_count'] is currently showing the whole results, whereas I need showing a total count grouped by client
Sorry if the explanation was confusing. I just added an image of View. As shown in the picture, both American Standard / Grohe & App Sinarmas have each 2 in total number = 4, whereas the actual total row is 1 of each column (client) = 2. I am sorry for my English.
It just solved by changing the query in Model:
function get_dailyprob()
{
$date = date('d-m-Y');
$query = $this->db->select('*, COUNT(*) as cnt')->like('created_at', $date)->group_by('client')->get('histprob');
return $query->result();
}
Then use foreach in View to get Count and Rows Result.
Related
i'm trying to count only the variable that fit the condition but the data i'm about to count is a result from formula and not inside the database
here is the code
if (isset($_GET['tanggal'])) {
$tgl=trim($_GET['tanggal']);
$material=trim($_GET['material']);
$proyek=trim($_GET['proyek']);
$sql="SELECT *, count(ketebalan-(toleransi/10)) as mintebal FROM tb_coring, tb_coredrill WHERE tb_coring.kode_material='$material' and tb_coring.kode_proyek='$proyek' and tb_coredrill.kode_material='$material' and tb_coredrill.kode_proyek='$proyek' and tb_coring.tanggal_coring='$tgl' GROUP BY tanggal_coring";
}
$hasil=mysqli_query($db,$sql);
$no=0;
while ($data = mysqli_fetch_array($hasil)) {
?>
<tr>
<td>Jumlah Data : <?php echo $data['mintebal']; ?></td>
</tr>
<?php
}
example i have 10 if i only echo mintebal but it will echo 8 data that fit the condition
or should i just add more column for the result of the formula on my database for easier count?
I'm kinda stuck here! I have to two tables free_members and domstic_members and I need to move selected rows from free_members tables to the domestic_members table. why I'm saying selected rows because of I at the end of every row in free_members tables there is an upgrade option which will move that row to the domestic_members table. I have the code but it's not working the way I want. right now what is happening is when I click on upgrade option it just copies the whole table records and sends it's to the other table. this here is the code
Controller
function upgradeprofile() {
// $this->load->database();
$this->load->model('freemember_model');
$this->freemember_model->upgrade();
}
model
function upgrade() {
$query = $this->db->get('free_members');
foreach ($query->result() as $row) {
$this->db->where('id', $member_id);
$this->db->insert('domestic_members', $row);
}
}
View
<center> Search Member:
<input type="text" name ='search' id='search' placeholder="Search a member"/></center>
<input type="hidden" name ='limit_from' id='limit_from'/>
</form>
<br><center><button type="button" onclick="CallPrint1('background12')">Print</button>
<div id="background12" class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Sr#</th>
<th><center>Full Name</th>
<th><center>Mobile Number</th>
<th><center>Membership# / CNIC</th>
<th><center>Email Address</th>
<th><center>Province</th>
<th><center>District</th>
<th><center>Tehsil</th>
<th><center>Union Council</th>
<?php /*?> <?php if($sessiondata['deletemembers']):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<th><center>Delete</th>
<?php endif;?>
<?php /*?><?php if($sessiondata['data_modification'] && $sessiondata['username'] != 'bilal.sabir' ):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<th><center>Print</th>
<th><center>Edit</th>
<th><center>Change Pwd</th>
<th><center>Upgrade</th>
<?php endif;?>
</tr>
</thead>
<tbody>
<?php $sr=0;?>
<?php foreach ($freemembers as $member): ?>
<tr><td><center><?php echo $sr+=1; ?></td><td><center><?php echo $member->first_name; ?></td>
<td><center><?php echo $member->mobile; ?></td><td><center><?php echo $member->cnic; ?></td>
<td><center><?php echo $member->email; ?></td>
<td><center><?php echo $member->province; ?></td><td><center><?php echo $member->district; ?></td><td><center><?php echo $member->tehsil; ?></td><td><center><?php echo $member->uc; ?></td>
<?php /*?> <?php if($sessiondata['deletemembers']):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<td><center>delete</td>
<?php endif;?>
<?php /*?><?php if($sessiondata['data_modification'] && $sessiondata['username'] != 'bilal.sabir' ):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<td><center>print</td>
<td><center>edit</td>
<td><center>change pwd</td>
<td><center>Upgrade</td>
<?php endif;?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
this is the view of my table free_members
Based upon your View, you have this...
index.php/admin/upgradeprofile/" . $member->id
So if $member->id = 100 the url will be
index.php/admin/upgradeprofile/100
So you are passing a member_id as mentioned in your model code BUT you are not getting it nor are you using the where correctly.
So you need to get a handle on the member_id...
This is ONE Solution/idea...This relies on you providing a correctly validated integer... You need to always Check/validate your inputs...
Controller
function upgradeprofile($member_id) {
// Need to check that $member_id is an integer
// To be added by the OP
$this->load->model('freemember_model');
// $member_id is passed in via the URL.
$this->freemember_model->upgrade($member_id);
}
Model
function upgrade() {
// Which member do we want to get from the free_members Table?
$this->db->where('id', $member_id);
$query = $this->db->get('free_members');
// Did we get a result? i.e was a valid member id passed in?
if($query !== false) {
$row = $query->row();
$this->db->insert('domestic_members', $row);
} else {
// Do nothing or handle the case where an illegal number was used...
}
}
Note: This code is not tested and is only to be used as a guide.
It can be refactored a number of ways but I am trying to keep it simple for now.
So please, do not just copy and paste this without at least "thinking" about what you are trying to do and how the code might be written to achieve it.
The main points here are...
1. You have to use a member id of some kind so you can retrieve the record for the free member so you can insert it into the other table.
2. You are providing this "member id" in the url so you need to extract it.
3. You can do that by either setting it as a parameter in the method being called... Or you can use segments ( look it up ).
So once you have the member id you can fetch the free member entry and insert it into the other table BUT What do you want to happen to the entry in the free members table because that is still going to be there and now you have two copies of the same information... Delete it?
If you need further explanation - ask.
One last point.
You should be making sure you fully understand what is you are doing and not just doing it because someone said to or you thought it was a good idea... Have a Good Reason and think of the implications...
I'm not familiar with Codeigniter but MySQL syntax should be this:
INSERT INTO table1 (table1.row1, table1.row2)
SELECT table2.row1, table2.row2
FROM table2
WHERE PUT_YOUR_CONDITION_IF_NEEDED
I've found this for Codeigniter.
How to retrieve student scores on each subject from database table infront of their names..
My Model
public function getscore($class, $term, $session)
{
$query = $this->db->query("SELECT scores FROM allscores WHERE class ='$class' AND term ='$term' AND session ='$session' AND scores !=0");
return $query;
}
controller
public function showscores()
{
$class=$this->input->post('classes');
$term=$this->input->post('term');
$session=$this->input->post('session');
$data['query_scores'] = $this->model->getscore($class,$term, $session);
$this->load->view('scoresheet', $data);
}
view page
<table>
<tr>
<?php
foreach ($query_scores->result() as $row)
{
?>
<td><?php echo $row->scores; ?></td>
<?php
}
?>
</tr>
</table>
Note: student name is listed horizontally on the left side of d page, subject names is displayed vertically as the heading.
My challenge is to display the score o each subject under d subject name for each students.
Your assistance in this regard would be very appreciated.
public function getscore($class, $term, $session)
{
$query = $this->db->query("SELECT scores FROM allscores WHERE class ='$class' AND term ='$term' AND session ='$session' AND scores !=0");
return $query-result();
}
Use result() to format and show thing from database.
Use following table format to display subject names
<table>
<thead>
<tr>
<td> SUB1 </td> <td> SUB2 </td> <td> SUB3 </td>
</tr>
</thead>
Now use your code for Corresponding Content.
The exact PHP code for displaying the subject score will depend on your database structure. For more clarification, please share your database table structure.
try this.
Model:
note: change field name and query structure to match yours
normaly this will require a join but this is a basic example for you to get the idea
public function getscore($class, $term, $session){
$query = $this->db->query("SELECT scores,student_id ,student_name, subject_id,subject_name , FROM allscores WHERE class ='$class' AND term ='$term' AND session ='$session' AND scores !=0");
return $query;
}
Controller:
public function showscores(){
$class=$this->input->post('classes');
$term=$this->input->post('term');
$session=$this->input->post('session');
$data['query_scores'] = $this->model->getscore($class,$term, $session);
// create array to hold the new organized data;
$list = array();
// list['scores'] will hold the student scores;
// list['students'] = will hold the student names
// list['subjects'] = will hold the subjects names
// loop throught the result
foreach ($query_scores->result() as $row){
$list['scores'][$row->student_id][$row->subject_id] = $row->scores;
$list['students'][$row->student_id]= $row->student_name;
$list['subjects'][$row->subject_id]= $row->subject_name;
}
$this->load->view('scoresheet', $list);
}
view page:
<table>
<tr>
<?php
foreach ($subjects as $subject){
echo "<td>".$subject."</td>"; // will display subjects names on the first row
}
?> </tr> <?php
$column = 0;
foreach ($scores as $key=>$element){
echo "<tr>";
echo "<td>".$students[$key]."</td>"; // will display student names on the first col
foreach ($element as $subKey=>$subelement){
echo "<td>".$subelement."</td>";
}
echo "<tr>";
<?php
} ?>
</table>
I'm working with symfony 1.4 and Doctrine. I'm writing an app about some pubs/bars, and I've got 4 tables:
products
orders
product_order
pubs.
I want to get the times all products have been ordered in the first pub (i.e. pubs.id = 1). This is what I've got, but I can only get the sum of the first product (products.id = 1) and I need the sum of all of them, in this case there are two different products in my db.
ProductOrderTable:
public function ordersGetCount(){
$q = Doctrine_Query::create()
->from('ProductOrder l')
->innerJoin('l.Order p ON l.id_order = p.id')
->select('SUM(l.amount) as units')
->andWhere('p.id_pub = 1')
->groupBy('l.id_product')
->orderBy('p.id');
return $q->execute();
}
Here my action class:
$this->resultCount= Doctrine_Core::getTable('productorder')->ordersGetCount();
And here my template:
for($i=0; $i<2; $i++){
echo "<tr>";
echo "<td>".$resultCount[0]->getUnits()[$i]."</td>";//
echo "<td>1</td>";
echo "<td>1</td>";
echo "</tr>";
}
Please need help :)
I think there's nothing wrong with your query, but you should have a look at how you display your results.
echo "<td>".$resultCount[0]->getUnits()[$i]."</td>";
Firstly, you're always referring to the first element in the $resultCount array. Secondly, I'm not sure if you can use a getter for a virtual column (you're not using a column which is mapped to your model.
So I would go with something like this:
In the ordersGetCount I would use
return $q->fetchArray();
This will return an array of arrays, not an array of objects, and will allow you to access the virtual column units.
To display the results:
<?php foreach ($resultCount as $row): ?>
<tr>
<td>
<?php echo $row['units']; ?>
</td>
<td>1</td>
<td>1</td>
</tr>
<?php endforeach ?>
EDIT:
This is quite strange ;) Can you try to build the query this way: (in theory it should be the same):
$q = $this->createQuery('l')
->select('l.id_product, sum(l.amount) as units')
->innerJoin('l.Order')
->where('p.id_pub = 1')
->groupBy('l.id_product')
->orderBy('p.id');
You must try remove
->groupBy('l.id_product')
it reduces you results to one product.
I have these two objects:
$userinfo->pilotid;
$departures->total;
I'm trying to get $departures->total for specific pilotid in $userinfo = $userinfo->pilotid.
However, I'm not sure how can I link them so it echoes A for B. I have something like this but it does not display anything.
<?php echo $pilotid->$departures->total; ?>
Additionally, the first object is called like this:
$pilotid = Auth::$userinfo->pilotid;
This is the structure of the table where the objects are gathered from, using a query.
Stemming from the data provided by the OP, I am assuming, that $departures has a 1:n relationship with $userinfo, $userinfo being the 1 containing the pilotid.
So, in oder to find out how many departures that pilot had in total, there's two possible ways, one by using a subquery, which would mean something like this:
SELECT (SELECT COUNT(*) FROM `departures` WHERE `pilot_id` = ID) as total, * FROM pilots;
In this case, your total would be in the total column of your $userinfo query.
The second attempt makes use of actual PHP. In this scenario, you do the counting yourself.
First step: Getting the pilot information:
$userinfo = array();
while($row = fetch()) {
$row->total = 0;
$row->departures = array();
$userinfo[$row->pilotid] = $row;
}
These lines will give you the pilot data keyed to their IDs in an array.
Step two. Glueing the departures to the pilots.
while($row = fetch()) {
if(isset($userinfo[$row->pilotid])) {
$userinfo[$row->pilotid]->departures[] = $row;
++$userinfo[$row->pilotid]->total;
}
}
If this isn't what you're looking for, I will be needing more information from you, however like this you will be able to get the departures of the pilots either by making use of the total variable in the $userinfo object, or by simply calling count on the departures array.
Another variant, which keeps the actual departures and the pilots apart would look like this:
First step: Getting the pilot information:
$userinfo = array();
while($row = fetch()) {
$row->total = 0;
$userinfo[$row->pilotid] = $row;
}
These lines will give you the pilot data keyed to their IDs in an array.
Step two. Glueing the departures to the pilots.
$departures = array();
while($row = fetch()) {
if(isset($userinfo[$row->pilotid])) {
$departures[] = $row;
++$userinfo[$row->pilotid]->total;
}
}
I hope you will find these suggestions useful.
Edit:
After a few additional information from the OP, I suggest changing the query used to access the information in question.
This is the original code by the OP
$dep_query = "SELECT COUNT(pilotid) as total, depicao, pilotid FROM phpvms_pireps GROUP
BY depicao, pilotid ORDER BY total DESC LIMIT 5";
$fav_deps = DB::get_results($dep_query);
foreach($fav_deps as $departure)
{
$dep_airport = OperationsData::getAirportinfo($departure->depicao);
$pilotid = Auth::$userinfo->pilotid;
?>
<tr class="awards_table1">
<td width="10%"><?php echo $departure->depicao; ?></td>
<td width="10%"><img src="<?php echo Countries::getCountryImage($dep_airport->country); ?>" /></td>
<td width="60%"><?php echo $dep_airport->name; ?></td>
<td width="20%"><?php echo $pilotid->{$departures->total}; ?></td>
</tr>
<?php
}
?>
First thing we'll change is the query used to get the departures. Why fetch all the information, if we actually only want the one of the pilot in question?
$pilotid = $userinfo->pilotid; //As per Chat discussion
$dep_query = "SELECT COUNT(depicao) as total, depicao FROM phpvms_pireps WHERE pilotid = $pilotid GROUP BY depicao ORDER BY total DESC LIMIT 5";
This query will return the Top 5 of the departures from the different airports, which have been run by the pilot in question. As for the rest:
$fav_deps = DB::get_results($dep_query);
if(is_array($fav_deps)) { //For the general use
foreach($fav_deps as $departure) {
$dep_airport = OperationsData::getAirportinfo($departure->depicao); ?>
<tr class="awards_table1">
<td width="10%"><?php echo $departure->depicao; ?></td>
<td width="10%"><img src="<?php echo Countries::getCountryImage($dep_airport->country); ?>" /></td>
<td width="60%"><?php echo $dep_airport->name; ?></td>
<td width="20%"><?php echo $departure->total; ?></td> //Here is the actually changed Layout code
</tr>
<?php
}
} else echo "This pilot didn't have any departures yet.";
?>
With these alterations, your code should output the desired result. It is completely untested though. However it should give you the right idea.
I think what you need is this (note the curly brackets):
<?php echo $pilotid->{$departures->total}; ?>
Unless I'm misunderstanding the question...