jeremy
jeremy

Reputation: 23

Change a td date color with PHP

I have to change my color td's date_client depending of current date. For example, if today is the birthday's client, this td s'date turns red (font, not background).

My HTML

<?php foreach ($rows as $row) : ?>
      <tr id_client=<?php echo $row["id_client"]; ?>>
        <td><?php echo $row["id_client"]; ?></td>
        
        <td><?php echo $row["client_birth_date"]; ?></td>
      </tr>
    <?php endforeach; ?>

My array https://i.sstatic.net/Hpzwl.png

Since i am in a loop foreach, each birthdate is unique.

I have tried this in PHP. PHP

 function date_color(){
      global $conn;
      $id_client = $_POST["id_client"];
      $client_date = $_POST["client_birth_date"];
      $calendar=$_POST["calendrier"];
    
      $calendar->date_format('Y-m-d'). $client_date->date_format('Y-m-d');
    
      if ($calendar==$client_date){
        echo "<font color='#FF0000'>$client_date</font>";
      }
        
    }

calendar is the date input in my screen.

I don't know how to do in JS neither. (the obstacle is how to get precisely the td's date birth)

Any idea ?

Thank you.

Upvotes: 1

Views: 52

Answers (2)

jeremy
jeremy

Reputation: 23

My code now :

 $today = date('Y-m-d');
foreach ($rows as $row) :
    
    $birthday = $row["birthday"];

    $HowManyWeeks = date('W', strtotime($today)) - date('W', strtotime($birthday));

    $class = '';

    //birthday =
    if ($birthday == $today) {
      $class = ' class="font_red"';
    }
    //birthday= yellow or orange else black
    elseif ($HowManyWeeks == 1) {
      $class = ' class="font_yellow"';
    } elseif ($HowManyWeeks == -1) {
      $class = ' class="font_orange"';
    } else {
      $class = ' class="font_black"';
    }
  ?>
    <td id="id"><?php echo $row["id_client"]; ?></td>
    <td id="nom"><?php echo $row["nom_client"]; ?></td>
    <td id="prenom"><?php echo $row["prenom_client"]; ?></td>
    <?php echo  '<td id="date"'  . $class  . '>' . $row["birthday"] . ' </td>'; ?>

Upvotes: 1

Michel
Michel

Reputation: 4157

You can compare the database date with a variable containing todays date. If they match, apply a class to the <td>. Note: database date and todays date have to be in the same formate (Y-m-d).

  //create todays date once
$today = date('Y-m-d');

foreach ($rows as $row){
  $id=$row["id_client"];
  $birthday = $row["client_birth_date"];
  
    //create empty class
  $class = '';
    //compare birthday with today. If equal, set a class class
  if( $birthday == $today ){
    $class =' class="font_red"';
    }
  
    //output
  echo '<tr id=".$id.'">
          <td>'.$id.'</td>
          <td'.$class.'>'.$birthday.'</td>  //<-- apply class
        </tr>';
    }

And css

.font_red{
  color: red;
  }

Upvotes: 1

Related Questions