What I want:- I want to calculate the total working hours of my employees based on the working hours of multiple days.
My problem the total working hours ($total_hours) is not working.
My Model
class Attendence extends AppModel {
function add($data){
if (!empty($data)) {
$this->create();
if($this->save($data)) {
return true ;
}
}
}
function fetchdata() {
return $this->find('all', array('conditions' => array('Attendence.date' > '2014-04-01',
'AND' => array('Attendences.date' < '2014-04-21'),
)));
}
}
My Controller
class EmployeesController extends AppController {
public $uses = array('Employee', 'Attendence', 'InsertDate');
public function add()
{
if($this->Employee->add($this->request->data)==true){
$this->redirect(array('action'=>'index'));
}
}
public function index(){
$this->set('employees',$this->Employee->Fetch());
$this->set('attendence',$this->Attendence->fetchdata());
$this->set('dates',$this->InsertDate->fetchdate());
}
}
My View
<div class="index">
<table>
<thead>
<th>Num</th>
<th>Employee</th>
<th>Salary/Hour</th>
<th>Start Date</th>
<th>End Date</th>
<th>Total Hour</th>
<th>Total Salary</th>
</thead>
<?php
$id = 0;
foreach($employees as $e):?>
<? $id++ ?>
<tr>
<td><?php echo $e{'Employee'}{'id'} ?></td>
<td><?php echo $e['Employee']['firstname'], $e['Employee']['lastname'] ?></td>
<td style="text-align:center"><?php echo $e['Employee']['salary'] ?></td>'
<?php foreach($dates as $d):?>
<td><?php echo $d['InsertDate']['start_date'] ?></td>
<td><?php echo $d['InsertDate']['end_date'] ?></td>
<?php
$total_hours = 0;
foreach ($attendence as $et){
$ts1 = strtotime($et['Attendence']['in_time']);
$ts2 = strtotime($et['Attendence']['out_time']);
$diff = abs($ts1 - $ts2) / 3600;
$total_hours += number_format($diff,2);
}
//Total hours
echo '<td style="text-align:center">'.$total_hours.'</td>';
//Total Salary
echo '<td style="text-align:center">'.$total_hours*$e['Employee']['salary'].'</td>';
?>
<?php endforeach; ?>
<?php endforeach; ?>
</tr>
</table>
</div>
A programmer friend of mine gave me a solution. But I dont know how to implement in CAKEPHP
I am updating the solution also
Look at here :
$total_hours = 0;
foreach ($attendence as $et){
$ts1 = strtotime($et['Attendence']['in_time']);
$ts2 = strtotime($et['Attendence']['out_time']);
$diff = abs($ts1 - $ts2) / 3600;
$total_hours += number_format($diff,2);
}
The code shows you that there is an array. the array contains (attendance id and in_time and out_time in each point).
The Important thing is you should check how you fill this array.
In the above foreach that you generate the table by $employees array , you have the (employee_id) wich name (id) here
So you should write a new query in your view!!!In the middle of your first foreach and before second foreach
before this line :
$total_hours = 0
You have to write a query and fetch data from DB like this :
//SELECT * FROM attendences
WHERE attendences.date > '2014-04-23' AND attendences.date < '2014-04-30'
AND id=$e['Employee']['id'] // is your employee_id in your first array.
So when you fetched data , You have a new array named "$attendence"
Then , your second foreach(which calculates the salary and total hours) should work correctly
Related
I have a simple booking page. Already booked places belong to class "notAvailable". I want to use ajax to query username who booked certain slot. How can I achieve that?
$mydb = mysqli_connect('localhost', 'root', '', 'registration');
$myquery = "SELECT day, time FROM reserve";
$result = mysqli_query($mydb, $myquery);
$data_array = array();
while ($row = mysqli_fetch_assoc($result)) {
$data_array[$row['day']][] = $row['time'];
}
$arr2=array('Monday','Tuesday','Wednesday','Thursday','Friday');
foreach($arr2 as $v)
{
if(array_key_exists($v,$data_array))
{
$arr4[$v]=$data_array[$v];
}
}
$times = ['08:00', '09:00','10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00'];
?>
I used fetch_assoc funtion to get all booked slots from database just in once
And here I need ajax query to get username for each booked cell when mouse is on the cell.
<TABLE class="myTimetable">
<THEAD>
<TR>
<TH></TH>
<TH>Monday</TH>
<TH>Tuesday</TH>
<TH>Wednesday</TH>
<TH>Thursday</TH>
<TH>Friday</TH>
</TR>
</THEAD>
<TBODY>
<?php
foreach($times as $time)
{?>
<tr>
<?php
$nome=$nome+1;
echo $nome;
echo "<td>$time</td>";
foreach($arr4 as $aa => $bb)
{
if(in_array($time , $bb))
{
echo "<td class='notAvailable'></td>";
}
else{
echo "<td class='available'>mine</td>";
}
}
?>
</tr>
<?php
}
?>
</TBODY>
</TABLE>
I see no querys for the who reserved the time slot, but to show the data you can do something like this
<?php
$byHow = "for now unknown";
echo '<td class="notAvailable" data-by-who="'.$byWho.'">timeslot</td>';
in javascript
$('.notAvailable').on('mouseover',function(){
alert($(this).data('byWho'));
});
I want to query a database by making use of a whereMonth clause in laravel using a for loop but I am getting an empty array. If I replace $m in whereMonth clause with an integer like 7 it pulls the data.
<table class="table table-bordered table-hover expenses-report" id="expenses-report-table">
<thead>
<tr>
<th class="bold">Category</th>
<?php
for ($m=1; $m<=12; $m++) {
echo ' <th class="bold">' .date('F', mktime(0,0,0,$m,1)) . '</th>';}
?>
<th class="bold">year ({{\Carbon\Carbon::now()->format('Y')}})</th>
<?php
?>
</tr>
</thead>
<tbody>
#foreach ($categories as $category)
<tr>
<td>
{{$category->name}}
<?php
for ($m = 1; $m <= 12; $m++) {
if (!isset($netMonthlyTotal[$m])) {
$netMonthlyTotal[$m] = array();
}
$expense_results = $expenses->whereMonth('date',$m)
->whereYear('date', \Carbon\Carbon::now()->format('Y'))
->where('category', $category->id)
->get();
print_r($expense_results);
$total_expenses = array();
echo '<td>';
foreach ($expense_results as $expense) {
$expense = $expenses->where('id', $expense->id)->first();
$total = $expense->amount;
$totalTaxByExpense = 0;
// Check if tax is applied
if ($expense->tax != 0) {
$totalTaxByExpense+= ($total / 100 * $expense->tax);
}
$taxTotal[$m][] = $totalTaxByExpense;
$total_expenses[] = $total;
}
$total_expenses = array_sum($total_expenses);
// Add to total monthy expenses
array_push($netMonthlyTotal[$m], $total_expenses);
if (!isset($totalNetByExpenseCategory[$category->id])) {
$totalNetByExpenseCategory[$category->id] = array();
}
array_push($totalNetByExpenseCategory[$category->id], $total_expenses);
// Output the total for this category
if (count($categories) <= 8) {
echo $total_expenses;
} else {
// show tooltip for the month if more the 8 categories found. becuase when listing down you wont be able to see the month
echo '<span data-toggle="tooltip"
title="' . date('F', mktime(0, 0, 0, $m, 1)) . '">' . $total_expenses . '</span>';
}
echo '</td>';
}
?>
</td>
<td class="bg-odd">
{{array_sum($totalNetByExpenseCategory[$category->id])}}
</td>
</tr>
#endforeach
</tbody>
</table>
I basically want to return results matching the search query including the whereMonth
Can you replace this part
$query->whereMonth('date', $m);
with this
$query->whereMonth('date', (string) $m);
And then try again. I guess its not accepting integers.
I was able to get it to work by making use of Raw query
$rawQuery ="SELECT amount, id,tax FROM tblexpenses WHERE MONTH(date) = $m AND YEAR(CURRENT_DATE) AND category=$category->id GROUP BY id";
$expense_results = DB::select(DB::raw($rawQuery));
Though I would appreciate it if someone can help to translate this query to laravel
Couldn't find a specific answer to this so thought I'd ask. In short, I have a table that retrieves information from an API, based on data stored in my database and all I want to do is to get a total of certain, not all, columns from that table so that I can use them elsewhere on the site. As an example, let's use the Profit/Loss column and Total Divi. Do I have to somehow store the results as an array so that I can retrieve it elsewhere or is it something different?
<th>Profit/Loss</th>
<?php
for($x=0;$x<$y;$x++)
{?>
<tr>
<td class="input"><?php
if($pri[$x] > $lastprice[$x])
{
echo ($lastprice[$x]-$pri[$x]) * $vol[$x];
}
else if($pri[$x] < $lastprice[$x])
{
echo ($lastprice[$x]-$pri[$x]) * $vol[$x];
}
else
echo '0';
?></td>
<td><?php
$div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
$div = json_decode($div,TRUE);
foreach($div as $divi => $value) {
echo $value['stats']['dividendRate'];
}
?></td>
<td><?php
$firstno = floatval($vol[$x]);
$secondno = floatval($value['stats']['dividendRate']);
$sum = $firstno * $secondno;
print ($sum);
?></td>
</tr>
<?php } ?>
So I only left the profit/loss row/column as well as dividend amount (2nd column) and dividend total, just so you can see how I get these numbers in the first place.
Your requirement is, you want to use the profit/loss and total dividend column data of each row at the later stage of your code. What you can do is, create an empty array before the outermost for loop, and in each iteration of the loop, append the pair where key would be $x and value would be an array of profit/loss and total dividend column data.
<th>Profit/Loss</th>
<?php
$arr = array();
for($x=0; $x < $y; $x++){
?>
<tr>
<td class="input">
<?php
$profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
echo $profitOrLoss;
?>
</td>
<td>
<?php
$div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
$div = json_decode($div,TRUE);
$sum = 0;
foreach($div as $divi => $value) {
echo $value['stats']['dividendRate'];
$sum += (floatval($vol[$x]) + floatval($value['stats']['dividendRate']));
}
?>
</td>
<td>
<?php
echo $sum;
?>
</td>
</tr>
<?php
$arr[$x] = array('profitOrLoss' => $profitOrLoss, 'sum' => $sum);
}
?>
Update(1):
Based on your comment, all I want is to add up all the rows in Profit/Loss column together as well as rows in Total Divi column together. the solution code would be like this:
<th>Profit/Loss</th>
<?php
$profitOrLossSum = 0;
$dividendRateSum = 0;
for($x=0; $x < $y; $x++){
?>
<tr>
<td class="input">
<?php
$profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
$profitOrLossSum += $profitOrLoss;
echo $profitOrLoss;
?>
</td>
<td>
<?php
$div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
$div = json_decode($div,TRUE);
$sum = 0;
foreach($div as $divi => $value) {
echo $value['stats']['dividendRate'];
$sum += (floatval($vol[$x]) + floatval($value['stats']['dividendRate']));
$dividendRateSum += floatval($value['stats']['dividendRate']);
}
?>
</td>
<td>
<?php
echo $sum;
?>
</td>
</tr>
<?php
}
$arr = array('profitOrLossSum' => $profitOrLossSum, 'dividendRateSum' => $dividendRateSum);
?>
Sidenote: If you want to see the complete array structure, do var_dump($arr);
I'm building an analytics tool for some Facebook pages where I can view page information and statistics.
The problem is that it takes a long time to load the data using FQL, almost 50 seconds to load the page fully. The problem is that it needs to request a query for each day when I want to know all the new likes within a month and then count them all up.
These are the functions I'm using:
function getmetrics($objectid, $metrics, $end_time, $period){
global $facebook;
$fql = "SELECT value FROM insights WHERE object_id=$objectid AND metric='$metrics' AND end_time=end_time_date('$end_time') AND period=$period";
$response = $facebook->api(array(
'method' => 'fql.query',
'query' =>$fql,
));
if (!empty($response)){
return $response[0]['value'];
}
else{
return "no results found";
}
}
function getdailymetrics($objectid, $metrics, $end_time , $days ){
global $facebook;
$total = 0;
do {
$amount = getmetrics($objectid, $metrics, $end_time, '86400');
$total += $amount;
$pieces = explode("-", $end_time);
$end_time = date("Y-m-d", mktime(0, 0, 0, date($pieces[1]),date($pieces[2])-1,date($pieces[0])));
$days--;
} while($days > 1);
return $total;
}
On the front end:
<table>
<tr>
<td>Total likes</td>
<?php
$like1 = getmetrics($samsung, 'page_fans', '2012-01-29', '0');
$like2 = getmetrics($samsung, 'page_fans', '2012-02-26', '0');
$likep = round((($like2/$like1)-1)*100, 2);
?>
<td><?php echo $like1; ?></td>
<td><?php echo $likep; ?>%</td>
<td><?php echo $like2; ?></td>
</tr>
<tr>
<td>New Likes</td>
<?php
$newlikes1 = getdailymetrics($samsung, 'page_fan_adds', '2012-01-29', '28');
$newlikes2 = getdailymetrics($samsung, 'page_fan_adds', '2012-02-26', '28');
$newlikep = round((($newlikes2/$newlikes1)-1)*100, 2);
?>
<td><?php echo $newlikes1; ?></td>
<td><?php echo $newlikep; ?>%</td>
<td><?php echo $newlikes2; ?></td>
</tr>
<tr>
<td>Daily New Likes</td>
<td><?php echo round($newlikes1/28); ?></td>
<td><?php echo $newlikep; ?>%</td>
<td><?php echo round($newlikes2/28); ?></td>
</tr>
</table>
Is there a way to speed this up or is there a more efficient way?
You can try to reduce the amount of requests in two ways. First, you can use batch requests to send up to 50 queries to FB in one request. Also you can try to change your query, so that it would request insights for several days at once, like end_time in (values_list).
Also you could do some caching of the results.
And, though it depends on your certain case, maybe you could consider pulling insights with daemon (if you have the objects to pull data for), and storing it in the database.
I resolved the problem with a different method of fetching the data, using this function:
function getfromuntil($objectid, $metric, $start_time, $end_time){
global $facebook;
try {
$start_time = $timestamp = strtotime($start_time);
$end_time = $timestamp = strtotime($end_time);
$response = $facebook->api('/'.$objectid.'/insights/'.$metric.'?since='.$start_time.'&until='.$end_time);
} catch (FacebookApiException $e){
error_log($e);
}
$total = 0;
foreach ($response['data'][0]['values'] as $value) {
$total += $value['value'];
}
return $total;
}
So, i've been using codeigniter for a while and I've never had an issue running a query in my model and returning it to my controller which then passes it into my view where I access it as an object, like so:
MODEL (somemodel)
function getdata()
{
$query = $this->db->get('sometable');
return $query;
}
CONTROLLER (somecontroller)
function controldata()
{
$this->load->model('somemodel');
$data['dbdata'] = $this->somemodel->getdata();
$this->load->view('someview',$data);
}
VIEW (someview)
<?php
foreach($dbdata->result() as $row) {
echo $row->id;
echo $row->name;
echo $row->whatever;
echo "<br />";
}
?>
But now for whatever reason in 2.0 it's making use $dbdata->result_array() as $row instead.
Basically it's returning the results as an array instead.
It doesn't make any sense, has something changed in the new version?
Thanks,
So here's my code:
MODEL (admin_model)
function show_allproducts($sort,$order,$limit,$offset)
{
$this->db->select('products.id,productcategories.categoryname,products.name,products.internetspecial,products.added,products.modified');
$this->db->from('products');
$this->db->join('productcategories','products.productcategories_id = productcategories.id');
$this->db->order_by($sort,$order);
$this->db->limit($limit,$offset);
$query = $this->db->get();
if($query->num_rows() > 0)
{
return $query;
}
else
{
return FALSE;
}
}
CONTROLLER (admin)
function show_allproducts()
{
$data['title'] = 'All Products';
$this->load->library('pagination');
$config['base_url'] = 'http://'.$_SERVER['SERVER_NAME'].'/admin/show_allproducts';
$config['total_rows'] = $this->db->get('products')->num_rows();
$config['per_page'] = 10;
$config['num_links'] = 5;
$config['full_tag_open'] = '<div class="paggination right">';
$config['full_tag_close'] = '</div>';
$config['prev_link'] = '< prev';
$config['next_link'] = 'next >';
$config['cur_tag_open'] = '<a class="active">';
$config['cur_tag_close'] = '</a>';
$this->pagination->initialize($config);
$this->load->model('admin_model');
$data['tabledata'] = $this->admin_model->show_allproducts('name','ASC',$config['per_page'],$this->uri->segment(3));
$data['nav'] = 'admin/pagesections/nav';
$data['maincontent'] = 'admin/pages/show_allproducts';
$this->load->view('admin/template',$data);
}
VIEW (show_all_products)
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<?php if($tabledata) { ?>
<tr>
<th>ID</th>
<th>CATEGORY</th>
<th>NAME</th>
<th>ADDED</th>
</tr>
<?php foreach($tabledata->result() as $row) { ?>
<tr>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->categoryname; ?></td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->added;) ?></td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td>NO DATA</td>
</tr>
<?php } ?>
</table>
Unless you specify $dbdata->result_array() as $row , It wont return the results as array. The same code which you've posted must be working in CI 2.0.
If not, may be the problem with $this->db->get('sometable').
Try with $this->db->query('select * from sometable'). But as far as i know, both are same...
Ok folks, no lie, I found the freaking problem.
Looking at the fourth td where $row->added; is at, there's a close parantheses at the end of it that was causing 4 days of mayhem.
Kindest regards to all those who tried to help. Sometimes it doesn't matter how many eyes are on it I guess.