Date Comparison to update records - php

I'm getting records from a MySQL database with this PHP function:
function someFunction($date){
// all distinct records
$query = "select count(distinct column_name) as alias from table_name where DATE(date_column) = '$date'";
$result = $connection->query($query);
$row = $result->fetch_assoc();
return $row['alias'];
// end of all distinct records
}
Now what the below PHP code does is, get the day in the date, compute the week of the month it belongs to and stores it an an array.
//while fetch_assoc returns records
//$result1 query: "select * from table_name where DATE(date) between '$first_date' and date_add('$end_date',interval 1 day)"
while ($row1 = $result1->fetch_assoc()) {
$date = $row1['date'];
$start = 1;
$end = 7;
for ($i = 1; $i <= 5; $i++) {
if ((int) date('d', strtotime($date)) >= $start && (int) date('d', strtotime($date)) <= $end) {
if (!isset($arr1[$i]) || !isset($arr2[$i])) {
$arr1[$i] = 0;
$arr2[$i] = 0;
}
++$arr1[$i];
$arr2[$i] = someFunction(date('Y-m-d', strtotime($date)));
}
$start += 7;
$end += 7;
}
}
Consider 1st, 2nd and 3rd belong to the same week, 1st has 3 records, 2nd has 4 and 3rd has 1. The while loop will iterate 7 times, each value returned by the someFunction() overwriting the value in $arr2[$i].
So my question is, how will I be able to check if the previous iteration date value is equal to the current date value?

So my question is, how will I be able to check if the previous iteration date value is equal to the current date value?
Pseudocode:
$lastValue = …; // initialization with a value that does not occur in the actual values,
// such as NULL, empty string, …
while(…) {
if($currentValue == $lastValue) {
// do something
}
else {
// do something else
}
// …
$lastValue = $currentValue; // set current value for next loop interation
}

Related

Get all months from a query including zero counts

I have this query now:
SELECT DATE_FORMAT(`dataNl`, \'%Y%m\') AS `Ym`, COUNT(*) AS `totale`
FROM `noleggio`
GROUP BY `Ym`
This help to get data for each month, but if a month with 0 value, this doesn't exist in the database, so I can't get it. I need a query that add remaining month setting the COUNT field to 0.
I made a PHP code to add months with 0 value into the array, but it only works if the year is only one, if I want to get more, this needs a lot of tricky code, I think there could be a solution with SQL.
This is the PHP code:
$t = array();
$m = array();
foreach ($months as $val) {
$t[] = $val['totale'];
$m[] = $val['Ym'];
}
for ($i = 0; $i < 12; ++$i) {
if (in_array($i + 201801, $m) == false) {
array_splice($t, $i, 0, 0);
}
}
Here is a PHP solution which requires min and max dates from the database:
// use the query SELECT MIN(dataNl), MAX(dataNl) FROM ... to
// find the first and last date in your data and use them below
$dates = new DatePeriod(
DateTime::createFromFormat('Y-m-d|', '2018-01-15')->modify('first day of this month'),
new DateInterval('P1M'),
DateTime::createFromFormat('Y-m-d|', '2018-12-15')->modify('first day of next month')
);
// assuming $rows contain the result of the GROUP BY query...
foreach ($dates as $date) {
$datestr = $date->format('Ym');
$index = array_search($datestr, array_column($rows, 'Ym'));
if ($index === false) {
echo $datestr . ' -> 0' . PHP_EOL;
} else {
echo $datestr . ' -> ' . $months[$index]['totale'] . PHP_EOL;
}
}
Try the below query:
SELECT DATE_FORMAT(`dataNl`, \'%Y%m\') AS `Ym`, COUNT(*) AS `totale`
FROM `noleggio`
GROUP BY MONTH(`dataNl`)

Comparing values from a database using a while loop

I have a MySql table where I saved all workers names and the dates workers have to work on. I want to show a list containg all days of the current month and the worker names who have to work on the day that corresponds to them. Example:
February
1
2
3 - John Wick
5
6 - Martha Beck
etc.
This is the code I have in PHP but the loop is not working. I just get a list from 1 to 30 but it is not showing the data from database. If I run the loop without the (while ($n < 31)), I get all the records from database but I want to show the names just beside the day that correspond.
<?php
mysql_select_db($database_nineras, $nineras);
$query_res = sprintf("SELECT res_id, res_dateini, res_datefin, res_name FROM reservas ORDER BY res_dateini DESC");
$reservas = mysql_query($query_res, $nineras) or die(mysql_error());
$rreser = mysql_fetch_assoc($reservas);
$treser = mysql_num_rows($reservas);
$n = 1;
while ($n < 31) {
do {
++$n;
if ($n == date('d', strtotime($rreser['res_dateini']))) {
echo $n . ' - ' . $rreser['res_name'];
}
else {
echo $n;
}
} while ($rreser = mysql_fetch_assoc($reservas));
}
?>
The problem with your code is that the do-while loop is fetching all the rows returned by the query. So when you get to the second iteration of the while loop there's nothing left to fetch.
Rather than fetch the rows from the database each time through the loop, you can fetch them once and put them into an array whose index is the day numbers. Then you can loop through the days and print all the rows for each day.
Use date('j', ...) to get the date without a leading zero. Or change your SQL query to return DAY(res_dateini).
$results = array();
$reservas = mysql_query($query_res, $nineras) or die(mysql_error());
while ($rreser = mysql_fetch_assoc($reservas)) {
$d = date('j', strtotime($rreser['res_dateini'])));
$results[$d][] = $rreser['res_name'];
}
for ($day = 1; $day <= 31; $day++) {
echo "$day - " . (isset($results[$day]) ? implode(", ", $results[$day]) : "") . "<br>\n";
}
DEMO

logic to loop through records containing timestamps

I need help with some logic when handling timestamps.
I have a table with a few hundred records, each record has a field witch contains a timestamps.
I have $NextAuditStamp, this field is populated via a user input script which converts dates to timestamps.
Now I need to loop through each record and return all the records where the $NextAuditStamp minus $n is greater than $NowTime. Here is the test code I am currently work with to try and get the logic working:
$NowTime = time();
$Flag = "";
$n = 2635250; // this is a fixed timestamp representing 1 month
$NextAuditStamp = strtotime($_POST['NextAuditDate']);
if($NowTime - $n > $NextAuditStamp) {
$Flag = 1;
} elseif($NowTime > $NextAuditStamp) {
$Flag = 2;
} else {
$Flag = "0";
}
$NextAuditStamp minus $n is greater than $NowTime
Your test for $Flag = 1 does the opposite, guess you want
if($NextAuditStamp - $n > $NowTime) {...}

How can I generate a random number every x amount of months?

Starting with the number 9 and using php, I would like to be able to count up from there, and echo out the next number in increments of 1.
So, number 9, then after 1 month the number would change to 10, then another month 11, then 12 etc., with no maximum number/stop point.
How can I accomplish this? So far I have the below code.
$number = 9;
$output = $number + 1;
echo $output;
Is there a way to set this to increase once a month?
You can do this with the PHP date()-function. This is one example of doing it if you are not dependent on the day of the month, but adding day functionality is possible and should be quit easy.
$startNumber = 9;
$startYear = 2015;
$startMonth = 9;
$currentYear = intval( date( "Y" ) );
$currentMonth = intval( date( "n" ) );
$monthsToAdd = ( ( $currentYear - $startYear ) * 12 )
+ ( $currentMonth - $startMonth );
echo $startNumber + $monthsToAdd;
From your question, I'd say:
$number = 9;
$output = date('n') + $number;
echo $output;
But that depends on what you are trying to accomplish. You can also wrap the number around the date() with a modulo.
However this is nothing random. If you want to create a random number every month like your topic suggests, use the month as the random seed.
srand(date('n'));
$number = rand();
a very inefficient way would be
<?php
function increm($duration){
while ($i<$duration) {
$i++;
}
return true;
}
$number = 9;
$start = time();
$i = 0;
while (1){
increm(3600*24*30);
$i++;
// Do your code
}
?>
this script would have to be run continuously for months.
A better way would be
<?php
$number = 9;
if(!file_exists('date.txt')){
$date=date('n');
file_put_contents( (string)time());
$date = 0;
}
else{
$date= file_get_contents('date.txt');
$date= date()-(int)$date;
$date= floor($date/(24*3600*30));
}
// do whatever you may
?>
But this script would increase it whenever called as the first open date would be stored. Will work forever (till UNIX can timestamp).
for this purpose you have to store the number in the database, compare with current unix timestamp and update it when the new month is reached.
2 database columns: count_month int(10) and next_month int(10) where next_month will contain the unix timestamp of the first day of the next month. you can run it with cronjobs or on production.
<?php
$now = strtotime("now");
$next_month = strtotime("first day of next month");
if ($query = $dbconnect->prepare("SELECT next_month FROM table1")) {
$query->execute();
$query->bind_result($compare_time);
$query->store_result();
$row_count = $query->num_rows;
if ($row_count > 0) {
while ($query->fetch()) {
if ($compare_time < $now) { // you reached the 1th of the next month time to update
if ($query2 = $dbconnect->prepare("UPDATE table1 SET count_month=count_month +1, next_month=?")) {
$query2->bind_param('i', $next_month);
$query2->execute();
$query2->close();
}
}
}
}
$query->free_result();
$query->close();
}
?>

php/mysql ordered random dates

I found this great function on SO whilst looking for a way to generate random dates between two fixed timestamps:
function randomDate($start_date, $end_date)
{
// Convert to timestamps
$min = strtotime($start_date);
$max = strtotime($end_date);
// Generate random number using above bounds
$val = rand($min, $max);
// Convert back to desired date format
return date('Y-m-d H:i:s', $val);
}
Source and credit
but I am looking for a way for the dates to be generated in order (start date to end date) as I have used it to generate dates to insert into a database.
The problem is my posts are ORDER BY id DESC and using the function "as is" being that they are random the dates end up out of sync.
ie:
post id 4 - date = 2010-07-11 14:14:10
post id 3 - date = 2012-02-22 18:23:21
post id 2 - date = 2011-03-17 13:52:47
post id 1 - date = 2011-08-14 15:33:50
and I need them to be in sync with the post id.
Now your thinking why not change the query to ORDER BY date DESC instead? ...well that would mess up 99% of code I have already written as there are other columns/rows dependent on it being ORDER BY id DESC and so ordering the dates when being inserted into the database is the only solution.
update:
this is what I tried using madfriend code but all dates are the same where have I gone wrong?
function randomDate($startdate, $enddate){
$min = strtotime($startdate);
$max = strtotime($enddate);
$val = rand($min, $max);
return date('Y-m-d H:i:s', $val);
}
$query = "SELECT * FROM foo";
$num = mysql_num_rows(mysql_query($query));
$randate = randomDate('2010-07-12 09:13:40', '2012-06-12 09:13:40');
$dates = array($randate);
for ($i = 0; $i < $num; $i++) {
$dates[] = randomDate($startdate, $enddate);
}
sort($dates);
while($date = array_shift($dates)) {
$update = "UPDATE foo SET date='{$date}'";
mysql_query($update);
}
plus getting
Notice: Undefined variable: startdate
I'm not quite sure whether you are talking about creation or modification of existing rows.
Updates: basic idea here is quite simple. First, count number of posts with SELECT COUNT(*) FROM your_posts_table query. After that:
// $num is number of posts
$dates = array();
for ($i = 0; $i < $num; $i++) {
$dates[] = randomDate($startdate, $enddate);
}
sort($dates); // Sort dates in ascending order
while($date = array_shift($dates)) {
// now $date won't be lower than it was in previous iterations.
// use it to update your table
}
Insertions: If you are talking about insertions and want to make latest post date random but biggest, here's what you do:
First, select last added post date.
Second, call randomDate with $startdate set to the date of last added post.
Last, insert new row with this date.
function randomDate($startdate, $enddate){
$min = strtotime($startdate);
$max = strtotime($enddate);
$val = rand($min, $max);
return date('Y-m-d H:i:s', $val);
}
$query = "SELECT * FROM foo";
$num = mysql_num_rows(mysql_query($query));
$randate = randomDate('2010-07-12 09:13:40', '2012-06-12 09:13:40');
$dates = array($randate);
for ($i = 0; $i < $num; $i++) {
$dates[] = randomDate($startdate, $enddate);
}
sort($dates);
while($date = array_shift($dates)) {
This query updates all rows in one go:
$update = "UPDATE foo SET date='{$date}' ";
mysql_query($update);
}
Probably were wanting to use
$update = "update foo set date='{$date}' where id = (select id from foo where date is not null order by id limit 1)";
(for that to work you need to set each date in the db to null before you start updating: update foo set date=null)
Also you shouldn't be using myslq_query..

Categories