0

I'm working on a website that manages food. Keeping track of expiration dates and the such.

When a users dashboard loads, it shows a list of the food items they've currently added along with info about them, Brand, Location (Fridge,Pantry,Freezer), and expiration date.

I have the items in a html table, drawing their values from php echos of the rows of a food table I created.

What I want to do is change the text of the expiration date to red when there is about a 3 day difference between the current date and the set expiration date.

Here's my code for putting the values in the table.

       <?php 

while($rows = mysql_fetch_array($sql2))

    {
?> 

            <tr>
              <td><b><?php echo $rows['Name'] ?></td>
              <td><b><?php echo $rows['Brand'] ?></td>
              <td><b><?php echo $rows['Type'] ?></td>
              <td><b><?php echo $rows['Container'] ?></td>
              <td><b><?php echo $rows['ExpirationDate'] ?></td>
              </tr>


            <?php

    }
    ?>

$sql2 holds a query of all the foods owned by the user.

So how would I create a conditional that would make this work out?

2 Answers 2

2
$date1 = new DateTime("now");
$date2 = $rows['ExpirationDate'];
$difference = $date1->diff($date2);
$days = $difference->d;
$class = '';
if ($days <= 3)
    $class = 'class="expired"';

Then add the $class variable to each table cell. If the difference between dates is 3 days or less, it will add class="expired" otherwise it will add nothing. Then just style the .expired class to have red text.

You will most likely have to format your $date2 variable, but how to do that depends on the format it's currently in...

Sign up to request clarification or add additional context in comments.

Comments

0

You can assign a different class to the expiration date when it's getting close.

Something like:

<td><b><?php 
     $exptime = strtotime($rows['ExpirationDate']);
     if ($exptime - time() < 3*24*60*60){
         $class = 'expBad';
     }else{
         $class = 'expOK';
     }

     echo "<span class=\"$class\">".$rows['ExpirationDate']."</span>" ?></td>

Then in your .css you can define the class expBad to be red.

   span.expBad {
      color: red;
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.