rowCount for items over 45 days old - php

I have a table and use this to show me how many days the widgets have been in stock, this is the code I am using for this
$getWidgets = $db->prepare("SELECT * FROM widgettracker WHERE id=id");
$getWidgets->execute();
$widgets = $getWidgets->fetchAll();
foreach ($widgets as $widget) {
$startDate = new DateTime();
$endDate = new DateTime($widget['dadded']);
$diff = date_diff($endDate,$startDate);
$days = (int) $diff->format('%a');
I have info boxes at the top of the screen giving me different widget info, what I wanted is one of these info boxes to give me a total of how many widgets have been in stock for 45 days +
I am using this code for other sections of the site but I hate working with days/dates and simply cannot get my head round where and how I put the count in for the ones over 45 days
$widget45days = $db->query("SELECT id FROM widgettracker WHERE widgetstatus='Widgets for Sale'");
$widget45dayscounted = $widget45days->rowCount();

The query should look like this:
SELECT *
FROM widgettracker
WHERE dadded < NOW() - INTERVAL 45 DAY;

Related

For php does not increase

I have a table of users in a database, where I have the following fields:
id_usuario
login
passwd
dias_disponibles (Fixed users have 24 days available)
fecha_ingreso (Date entry in company)
tipo_usuario (Fixed or Temporary)
Each user can make a vacation request. The user admin is responsible for adding the new users. My problem is with temporary users. A temporary user will have the available days according to the months worked up to one year. For every month worked, dias_disponibles is increased by 2. For example, if user1 since joining the company, it has been working for 2 months now it will have 4 dias_disponibles and so on until it takes 12 months, then from there, it will always be 24 dias_disponibles . I have this function that calculates the difference of months since I joined the company until today:
function difmeses($fechaingreso){
$fechainicial = new DateTime($fechaingreso);
$fechaactual = (new DateTime)->format('Y-m-d H:i');
$fechafinal = new DateTime($fechaactual);
$diferencia = $fechainicial->diff($fechafinal);
$meses = ( $diferencia->y * 12 ) + $diferencia->m;
return $meses;
}
My question is what to use so that it increases until 12 months in the company, if it takes 12 months, stop. I have created this for, but I do not know how to continue so that it increases in 2 days available:
$mes = difmeses("2018-03-15 00:00");
for($i = 1; $mes <= 12; $i++){
mysql_query("update sec_users set dias_disponibles = dias_disponibles + 2 where login = 'user1'");
}
It does not do what I want very well.
First of all your logical problem
The problem you have is in your last part of the code
$mes = difmeses("2018-03-15 00:00");
for($i = 1; $mes <= 12; $i++){
mysql_query("update sec_users set dias_disponibles = dias_disponibles + 2 where login = 'user1'");
}
First of all, there is no need at all to use a for loop here. You overwrite the update commands of the previous runs of the loop, so at the end only the last one will be in the table. Because of this you can work with the last one without a loop.
Sencond you got a really simple formula here: Free days = (month worked * 2) max 24. Just write that down as code:
$mes = difmeses("2018-03-15 00:00");
$dias = max($mes * 2, 24);
mysql_query("UPDATE sec_users SET dias_disponibles = $dias where login = 'user1'");
Now another huge problem
Do not use the mysql_ functions. They are deprecated! Instead use the mysqli_ functions or PDO and read about prepared statements.

How to build a time based pricing system with overlaps

I am currently working on a reservation system in PHP (Laravel 5) and I can't figure out how to build a time based pricing system that calculates the totalprice with overlaps. Reservations are stored with the following fields
Reservations (Table)
begindate_time (DateTime)
enddate_time (DateTime)
price (decimal(10,2))
I have a prices table to lookup the prices for the input begintime and endtime which looks like this:
Prices (Table)
id (INT)
price (decimal(10,2))
begin_time (time)
end_time (time)
dayOfTheWeeks (varchar(255))
The begin_time/end_time can vary from 00:00:00 to 23:59:59 and the dayOfTheWeeks is a string with days for instance monday,tuesday,wednesday. I know there should only be one value for each field, but I was to lazy to make a whole table for the days of the week.
Than you have a activity that is linked to a reservation that has different prices based on the time the activity this is linked to a price_activity table, because prices can have different activity's
activity_price (Table)
id
activity_id (INT)
price_id (INT)
I tried to get the prices foreach activity and day like this, than I have them sorted and can try to loop through them and substract the endtime of the price minus the begintime of the reservation. This is what I came up with but it is not working...
foreach($activity->prices()->orderBy('begin_time','asc')->get() as $price){
$whichDayArray = explode(',',$price->dayOfTheWeeks);
if(in_array($dayToday,$whichDayArray)){
$prices = array();
if(strtotime($price->end_time) > strtotime($input['begintime']) && strtotime($price->begin_time) < strtotime($input['endtime'])){
$prices[] = array('id' => $price->id,'price' => $price->price,'beginTimePrice' => $price->begin_time, 'endTimePrice' => $price->end_time);
}
}
}
This is a lot of code and I have my prices that are overlapping my reservation now, but how do I calculate the amount of time a reservation is in a price. I think it can be done much easier and better than the above.
I've solved my own question. Hoping to help others with a similar problem, I would like to explain how I solved my problem.
After dumping my variables and making a visualization of the problem as shown below I found that the problem was related to my query.
[--pricerange1--][--pricerange2--][--pricerange2]
[----------reservation-----------]
I have to get all the prices for a activity on a given day of the between the begintime of the reservation and the endtime of a reservation, after that I have to check if there is one price, two prices or more than 2 prices. Than calculate the number of hours that a reservation is in a range and multiply it by the price a range. The code for this will look like this:
$begintijd = \Carbon\Carbon::createFromTime(16,30);
$eindtijd = \Carbon\Carbon::createFromTime(20,30);
$activiteit = \App\Activiteit::find(1);
$prijzen = $activiteit->prices()->where('eindtijd','>=',$begintijd->toTimeString())->where('begintijd','<=',$eindtijd->toTimeString())->orderBy('begintijd','asc')->get();
$prijzenArray = array();
foreach($prijzen as $prijs){
$whichDayArray = explode(',',$prijs->welkedagen);
if(in_array('maandag',$whichDayArray)){
$prijzenArray[] = array('prijs' => $prijs->prijs,'begintijdprijs' => $prijs->begintijd,'eindtijdprijs' => $prijs->eindtijd);
}
}
$countPrijzen = count($prijzenArray);
if($countPrijzen == 1){
$aantaluur = $begintijd->diffInMinutes($eindtijd) / 60;
$totaalprijs = $aantaluur * $prijzenArray[0]['prijs'];
echo('range1');
}
if($countPrijzen == 2){
$aantaluurrange1 = \Carbon\Carbon::createFromFormat('G:i',$prijzenArray[0]['eindtijdprijs'])->diffInMinutes($begintijd) / 60;
$aantaluurrange2 = $eindtijd->diffInMinutes(\Carbon\Carbon::createFromFormat('G:i',$prijzenArray[0]['eindtijdprijs'])) / 60;
$totaalprijs = ($aantaluurrange1 * $prijzenArray[0]['prijs']) + ($aantaluurrange2 * $prijzenArray[1]['prijs']);
echo('range2');
}
if($countPrijzen > 2){
$aantaluurrange1 = \Carbon\Carbon::createFromFormat('G:i',$prijzenArray[0]['eindtijdprijs'])->diffInMinutes($begintijd) / 60;
$prijsrange1 = $prijzenArray[0]['prijs'] * $aantaluurrange1;
$prijsertussen = 0;
for($prijs=1;$prijs<($countPrijzen-1);$prijs++){
$aantaluurertussen = \Carbon\Carbon::createFromFormat('G:i',$prijzenArray[$prijs]['eindtijdprijs'])->diffInMinutes(\Carbon\Carbon::createFromFormat('G:i',$prijzenArray[$prijs]['begintijdprijs'])) / 60;
$prijsertussen += $prijzenArray[$prijs]['prijs'] * $aantaluurertussen;
}
$aantaluurlaatsterange = $eindtijd->diffInMinutes(\Carbon\Carbon::createFromFormat('G:i',$prijzenArray[$countPrijzen-1]['begintijdprijs'])) / 60;
$prijslaatsterange = $prijzenArray[$countPrijzen-1]['prijs'] * $aantaluurlaatsterange;
$totaalprijs = $prijsrange1 + $prijsertussen + $prijslaatsterange;
}

PHP total the number of days taken as leave within a yearly period

Am struggling about how to go about implementing this. I am fairly new with this language so any help would be greatly appreciated.
I have developed functionality whereby users are able to log annual leave, by selcting date to and date from etc. What I’d like to be able to do is be able to display how much leave is remaining / set a limit on logging leave they go over the 25 day limit within the yearly leave period.
I have looked at various php functions like date interval and date time, but can’t figure out how I would use them.
I would do something like this to tally up the total days taken.
<?php
$time_off_requests = array(0 => array('start_date' => '2015-01-01', 'end_date' => '2015-01-14'), array('start_date' => '2015-12-20', 'end_date' => '2016-01-02');
$total_days = 0;
foreach($time_off_requests as $time_out) {
$datetime1 = new DateTime($time_out['start_date']);
$datetime2 = new DateTime($time_out['end_date']);
$interval = $datetime1->diff($datetime2);
$total_days += (int)$interval->format('%a');
}
echo 'Out for a total of '.$total_days.' days this period.';
However if your data is in a MySQL database I would suggest doing that in the SQL Query unless you have a good reason not to.
$maxHolidays = 25;
$holidaysTaken = 0; //populate this from a database, Past holidays
$start = new DateTime('2015-07-26');
$end = new DateTime('2015-08-26');
$diff = $dStart->diff($dEnd);
if ($holidaysTaken + $diff < $maxHolidays) {
// Add the holiday
//add to the database
} else {
//reject the holiday
}
Something like that should work,
In reality though half day holidays are possible
You will likely have to check for holidays crossing years etc also depending on requirements

How to calculate duration in days?

I have to make a notification after 30 days.
foreach ($pdo->query($sql) as $row) {
$date = date_create($row['data']);
$laikotarpas = date_diff(new DateTime("now"), $date);
// var_dump($liko);
$liko = 30 - $laikotarpas->d;
I want correct result in days.
I have added a row at 2014.03.19 and this shows that left 3days to 30.
My goal is to achieve:
I add record at 2014.03.19 and get result how many days have passed from today. I thought that $laikotarpas->d gives a duration in days, but, when i do calculations to set the limit for 30days.
So my main problem is to get correct $liko, but I have no idea how.
I am adding my time using this code (using PDO):
$q->execute(array($name,
date("Y-m-d H:i:s", time())
);
In my database I use DATETIME. And i print that date from SQL using this php:
<?php echo date_format(date_create($data['data']), 'Y-m-d'); ?>
Is my way good? How to improve this?
-----edit-----
I have to use php5.2
Just got an idea, it takes only days and ignores months passed count. How to update that to count duration only in days?
If you want to find the difference between now and a date in the past, try something like this:
PHP >= 5.2.0
$then = '2014-03-19';
$date = new DateTime($then);
$now = new DateTime('now');
$diff = $date->diff($now);
echo $diff->days . ' days since ' . $then . PHP_EOL; // 58 days since 2014-03-19
PHP < 5.2.0
$date = strtotime($then);
$now = time();
$diff = $now - $date;
$days = round($diff / 60 / 60 / 24); // convert seconds to days and round off
Note: after understanding more about your problem, I highly suggest you filter your results based on date ranges in MySQL rather than PHP - it'll be easier and more economic and will reduce your potential risk for affecting data you didn't mean to. See Cull Larson's answer.
You could just use a query like this:
SELECT * FROM myTable WHERE DATE(signupDate) = DATE_SUB(NOW(), INTERVAL 25 DAY);
That will give you all results with a signup date that is 25 days old. If you have a flag in the table telling you whether you've notified them, you can pass that along too:
SELECT * FROM myTable WHERE notified=false AND DATE(signupDate) = DATE_SUB(NOW(), INTERVAL 25 DAY);
If you want to get every record 25 days or older, that hasn't been notified:
SELECT * FROM myTable WHERE notified=false AND DATE(signupDate) <= DATE_SUB(NOW(), INTERVAL 25 DAY);

How can I get unix times for the start and end of last twelve months in a loop?

I wish to print the totals of a column in my database for each month in the last year. The code I have so far to do this is:
$month = date("n");
$year = date("Y");
$loop = 12;
while($loop>1) {
$first = mktime(0,0,0,$month,1,$year);
$last = mktime(23,59,00,$month+1,0,$year);
$spendingData = mysql_query("SELECT * FROM spending WHERE date BETWEEN $first AND $last") or die(mysql_error());
$totalMonth = 0;
while($spending = mysql_fetch_array($spendingData))
{
$totalMonth = $totalMonth + $spending['amount'];
}
print "£".$totalMonth;
$loop = $loop-1;
print "<br>";
}
My quesiton is how, in the loop, do I adjust the times for each month? I thought about just taking a months worth of seconds away from the timestamps, but as I don't know how many days are in each month I don't think this will work. I also don't think I can just keep taking 1 away from the month figure as this will not account for years. I also don't want to hard code the figures in, as they will change with each new month.
How can I achieve this?
Thank you
You could do this rather trivially in MySQL:
SELECT MONTH(date) AS month, SUM(amount) AS amount
FROM yourtable
WHERE YEAR(date) = $year
GROUP BY MONTH(date)
without ever having to involve PHP for the date manipulation stuff.

Categories