Getting the sum of sales per year MYSQL PHP - php

I want to get the sales per year I have this code (please see below), that gets the column name and format it into (please see below). I have start date and end date I want to get the all the months between the two years. For example start date = 01/01/2017 and end date = 01/01/2018 I want go get the months between them and format it into SUM(JAN_2017) AS JAN_2017, etc and at the same time get the sum of all the months for the year 2017 and 2018.
SCREENSHOT OF MY TABLE
THIS IS MY COLUMN NAME SAMPLE (PLEASE REFER TO THE SCREENSHOT):
JAN_2017, FEB_2017 UPTO DEC_2017
SAMPLE OUTPUT OF MY CODE:
SUM(JAN_2017) AS JAN_2017, etc.
CODE:
$start = new DateTime($_POST["start"]);
$end = new DateTime($_POST["end"]);
$smonth = (int)$start->format('Y')*12+(int)$start->format('n');
$emonth = (int)$end->format('Y')*12+(int)$end->format('n');
$firstmonth = min($smonth, $emonth);
$lastmonth = max($smonth, $emonth);
$months = array();
for ($i = $firstmonth; $i <= $lastmonth; $i++) {
$thism = new DateTime(sprintf('%04d-%02d-01', intdiv($i, 12), $i % 12));
$months[] = strtoupper($thism->format('M_Y'));
}
$m_total = implode(',', preg_replace('/^(.*)$/', 'SUM($1) AS $1', $months));
$m_average = implode(',', preg_replace('/^(.*)$/', 'AVG($1) AS $1', $months)
);

Related

Check if any of the value in resultant array similar to values of existing array with codeigniter

I really need help to display a month list view in which deposit received month should be green in color and no-deposit month should be in red color.
I have stuck in comparing the array values. and I am using codeigniter.
I have a table with start-date and end-date by using this I have created an array to display all months in between these dates. Please find the code which I have used to do it below:
$datefrom = strtotime($showrangecalendar['chitdate_start']);
$dateto = strtotime($showrangecalendar['chitdate_end']);
$start_date = date('Y-m-d', $datefrom);
$end_date = date('Y-m-d', $dateto);
$day = 2.628e+6; // Day in Months
$format = 'Y-F'; // Output format (see PHP date funciton)
$sTime = strtotime($start_date); // Start as time
$eTime = strtotime($end_date); // End as time
$numDays = round(($eTime - $sTime) / $day) + 1;
$days = array();
for ($d = 0; $d < $numDays; $d++) {
$days[] = date($format, ($sTime + ($d * $day)));
}
This code got me the Days list and I have displayed this using foreach statement to a table.
Now I have another table (accounts) with columns such as ID, Book_number, Deposit_Amount and Deposit_Month. Here the problem starts I have fetched data from "accounts" and loaded to my view using the below code from controller
$data['show_account']= $this->Accounts_model->get_all_accounts($sess_data);
My Model (Accounts_Model) is as shown below:
public function get_all_accounts($id)
{
$this->db->select("*");
$this->db->order_by('book_id','desc');
$this->db->from("accounts");
$this->db->where('bh_id',$id);
$query = $this->db->get();
return $query->result();
}
If I run the belowcode:
foreach($show_account as $values){
echo $values->deposit_month;
}
Its getting me the array result of all deposit month. Suppose I have data as 2018-Sep and 2018-Oct, These 2 months column should turn green in the above mentioned $days array.
Hope I have explained my requirement clearly. Please help me with this as I am already spent long hours in this.
Thanks in Advance.
Updated:
Now could you please check my model as follows:
public function get_dep_month($bh_id)
{
$this->db->select('deposit_month');
$this->db->from('accounts');
$this->db->where('bh_id',$_SESSION['bh_id']);
$this->db->order_by('deposit_month','asc');
$query = $this->db->get();
return $query->result_array();
}
And My Controller is as follows:
$sess_data = $this->session->userdata('bh_id');
$data['depM_array'] = $this->Accounts_model->get_dep_month($sess_data);
Now please check my View as follows:
<?php
// option 2
foreach($days as $day) { // using your already exist $day for-loop for display
if (!in_array($day, $depM_array)){
$calhilight = "calgreen";
}
else{
$calhilight = "calred";
}
?>
<li class="<?php echo $calhilight; ?>"><?= $day ?></li>
<?php
}
?>
But as my doposit_month column having only 2 values ie: 2018-Sep and 2018-Oct, Instead of getting green color for those 2 values, I am getting Green for who li element. Not getting where I have done wrong.
This is the Current page view which I am getting, Actually I am expecting a calendar view with 2 green fields for 2018-Sep and 2018-Oct and all other fields in Red
Performed Var Dumb in arrays:
Pls check this screenshot
FYI:
Below is the code from where I am getting $days array.
<?php
$datefrom = strtotime($showrangecalendar['chitdate_start']);
$dateto = strtotime($showrangecalendar['chitdate_end']);
$start_date = date('Y-m-d', $datefrom);
$end_date = date('Y-m-d', $dateto);
$day = 2.628e+6; // Day in Months
$format = 'Y-F'; // Output format (see PHP date funciton)
$sTime = strtotime($start_date); // Start as time
$eTime = strtotime($end_date); // End as time
$numDays = round(($eTime - $sTime) / $day) + 1;
$days = array();
for ($d = 0; $d < $numDays; $d++) {
$days[] = date($format, ($sTime + ($d * $day)));
}
?>
Here $start_date & $end_date is fetching from another table named chitdate.
Thanks Again.
You can use array-diff or simple for-loop.
Consider the following simple example:
$days = array("2018-September", "2018-October", "2018-November", "2018-December");
$deposit_month = array("2018-September", "2018-October");
// option 1:
$diff = array_diff($days, $deposit_month);
// now $diff has: "2018-November" and "2018-December"
// option 2
foreach($days as $day) { // using your already exist $day for-loop for display
if (!in_array($day, $deposit_month))
// color in red as not found in "deposit_month"
else
// color in green
}
Nicer writing for that if can be as:
$color = in_array($day, $deposit_month) ? "Green" : "Red";

Getting the 3 consecutive year in Query

I have problem getting the year
I have here in my database year of 11/11/2016 - 11/13/2015 - 11/13/2014
the problem is I want to get that year just deducting current year
so if the current year is 2017 I want to get 2016,2015,2014 , and the next year
2018 the year will get is 2017,2016,2015
$selectmemberpaid = mysql_query("SELECT
memberid,StartDate,EndDate,tblpayments.activityname,amount_paid FROM
tblattend_activity LEFT JOIN tblpayments ON tblattend_activity.memberid =
.profile_id WHERE memberid='201400001'");
That is my query..
and this is my while loop
while ($rows = mysql_fetch_assoc($selectmemberpaid)) {
# code...
$dateTimestamp = strtotime($rows['StartDate']);
$year = date("Y", $dateTimestamp);
}
You can get the year from a date string by doing something like this:
$dateTimestamp = strtotime('2015-12-12');
$year = date("Y", $dateTimestamp);
echo $year;
Once you get it you can add or subtract to get the previous/next year (after converting the value into an integer).
I'm not sure I understand what you're asking but:
Query!
$rest = substr(date('d-m-Y'), 6);
$rep = $idz->query("SELECT * FROM stack1 where SUBSTR(date_depart, 6) < $rest
order by SUBSTR(date_depart,6) desc limit 3");
while ($row = $rep->fetch())
{
echo $row['date_depart'];
//echo "<br>";
}
$rep->closeCursor();
Result

Adding new items into PHP array and saving previous size of the array

I have the following code so far:
$months = array();
$numJoin = date("n",strtotime($me['joinTime']));
$numLast = date('n', strtotime('Dec 31'));
$numCurrent = date("n",strtotime('2016-06-01'));
array_push($months, date("F", strtotime($me['joinTime'])));
for($i = ($numJoin + 1); $i <= $numLast; $i++) {
if($numCurrent>$numJoin) {
$dateObj = date_create_from_format('!m', $i);
array_push($months, $dateObj->format('F'));
}
$numCurrent= -1;
}
What I'm trying to do here is to add into the array current month that kicks in, and save previous months in the array like for example:
Start month is -> May
June kicks in -> I add June into the array (now I should have May and June in array).
July kicks in -> I add July into the array (now I should have May, June and July in array).
How can I do this achieve this? Current solution works only for +1 month.. I can't add more than 1 month :/
P.S. New item should only be added when the new month kicks in, and previous content of the array should be saved...
Here we go, you need to check that your month is less than the current month or not. Check Online
$months = array();
$num = date("n",strtotime($me['joinTime'])); //join month number
$now = date("n"); //Current month number
for($i = $num; $i <= $now; $i++){
$dateObj = DateTime::createFromFormat('!m', $i);
array_push($months, $dateObj->format('F'));
}
print_r($months);
I'm still a little confused, but I think this is what you are after... all month names after the join month and until current month...
$me = array('joinTime'=>'2016-03-01');
$dtCurrent = strtotime($me['joinTime']);
$arrMonths = array();
while($dtCurrent < time()) {
$dtCurrent = strtotime("+1 month",$dtCurrent);
$arrMonths[] = date('F',$dtCurrent);
}
var_dump($arrMonths);

Finding Quarter of the year for current day and next four quarter

How to construct an array having elements current Quarter as first element and next four quarters as next elements.
Consider for the year 27-Nov-13,
array should contain elements as follows
$ac_quarters = array (AC4-13,AC1-14,AC2-14,AC3-14,AC4-14);
Please see me as novice to PHP programming.
Currently I have written code as shown below. Surely there gotta be better logic than this.
$date = "2013-1-13";
$d = date_parse_from_format("Y-m-d", $date);
if ($d["month"]==1 || $d["month"]==2 || $d["month"]==3) {
$ac_quarters = array (AC1-13,AC2-13,AC3-13,AC4-13,AC1-14);
}
To avoid special casing each month and looking it up, find out which quarter you're currently in by dividing the month number by 3, and then iterating through four quarters ahead.
$current = floor((date('n') - 1) / 3);
$year = date('y');
$quarters = array();
for ($i = 0; $i < 5; $i++)
{
$q = (($current+$i)%4) + 1;
$quarters[] = "AC" . $q . "-" . $year;
if (($current+$i+1)%4 == 0)
{
$year++;
}
}
var_dump($quarters);
We increment $year if the next quarter would be the start of a new year (which will give us 0 when using the modulo operator). You can use strtotime() if you want to change the startdate in the date() calls at the top.

PHP. How to get a bimonthly recurring event?

I'm trying many approaches but then I get stuck half way.
Let's say order was created today. I need to display when the next recurring order will happen. So I have order created June 13, 2012. Then I have set the schedule to bimonthly recurring order, every 1st of month. How to calculate when the next recurring order will happen? The answer is August 1st.
If someone can outline an approach it would be very useful, it doesn't have to be code. This is what I have so far...
// first, get starting date
$start_date_month = date('m', strtotime($start_date));
// get this year
$this_year = date('Y');
// if this month is december, next month is january
$this_month = date('m', $timestamp_month);
if($this_month == 12){
$next_month = 1;
// if this month is not december add 1 to get next month
}else{
$next_month = $this_month + 1;
}
// get array of months where recurring orders will happen
$months = array();
for ($i=1; $i<=6; $i++) {
$add_month = $start_date_month+(2*$i); // 2, 4, 6, 8, 10, 12
if($add_month == 13){$add_month = 1;$year = $this_year+1;}
elseif($add_month == 14){$add_month = 2;$year = $this_year+1;}
elseif($add_month == 15){$add_month = 3;$year = $this_year+1;}
elseif($add_month == 16){$add_month = 4;$year = $this_year+1;}
elseif($add_month == 17){$add_month = 5;$year = $this_year+1;}
elseif($add_month == 18){$add_month = 6;$year = $this_year+1;}
elseif($add_month == 19){$add_month = 7;$year = $this_year+1;}
elseif($add_month == 20){$add_month = 8;$year = $this_year+1;}
else{$year = $this_year;}
echo $what_day.'-'.$add_month.'-'.$year.'<br />';
$months[] = $add_month;
}
echo '<pre>';
print_r($months);
echo '</pre>';
I don't want to simply find what's the date in two months from now. Let's say order created June 1. Next recurring order is August 1. Then let's say now, today is September 1st, but next recurring order is October 1st. See my dilemma?
Just take the current month, so since it's June, we get 6. 6 mod 2 == 0. Next month is July, we get 7. 7 mod 2 == 1.
So just check if current month % 2 == (first month % 2).
Then just check if it's the 1st of the month.
In PHP modulus is defined with the percentage symbol.
$month = date('n');
$createdMonth = 6;
if($month % 2 == $createdMonth % 2){
// stuff
}
You might find the library called When useful for this (I'm the author).
Here is code which will get you the next 2 recurring monthly dates (from todays date):
include 'When.php';
$r = new When();
$r->recur(new DateTime(), 'monthly')
->count(2)
->interval(2) // every other month
->bymonthday(array(1));
while($result = $r->next())
{
echo $result->format('c') . '<br />';
}
// output
// 2012-08-01T13:33:33-04:00
// 2012-10-01T13:33:33-04:00
Taking this a step further, you likely only want to find the 2 first business days:
include 'When.php';
$r = new When();
$r->recur(new DateTime(), 'monthly')
->count(2)
->interval(2) // every other month
->byday(array('MO', 'TU', 'WE', 'TH', 'FR')) // week days only
->bymonthday(array(1, 2, 3)) // the first weekday will fall on one of these days
->bysetpos(array(1)); // only return one per month
while($result = $r->next())
{
echo $result->format('c') . '<br />';
}
// output
// 2012-08-01T13:33:33-04:00
// 2012-10-01T13:33:33-04:00
Also note, the code is currently under a rewrite -- it works well but it is a little confusing and not well documented.
strtotime to the rescue:
<?php
date_default_timezone_set('Europe/London');
$d = new DateTime('2012-01-31');
$d->modify('first day of +2 months');
echo $d->format('r'), "\n";
?>
Let's say you want the next six orders:
$order_date = '6/13/2012';
$start = date('Y-m-01', strtotime($order_date));
$order_count = 6;
$future_orders = array();
$next = strtotime('+2 months', strtotime($start));
while(count($future_orders) < $order_count){
$future_orders[] = date('m/d/Y',$next);
$next = strtotime('+2 months', $next);
}
This can, obviously, be improved upon, but it should get you started ...
I got this:
$today = new DateTime();
$target_date = $today->modify("first day of +2 months");
echo "Your event is on " . $target_date->format("d/m/Y") . "!";

Categories