larrybuntus larrybuntus - 3 months ago 14
MySQL Question

Date Comparison to update records

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?

Answer

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
}