Home > OS >  Change a td date color with PHP
Change a td date color with PHP

Time:07-22

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.stack.imgur.com/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.

CodePudding user response:

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 =' ';
    }
  
    //output
  echo '<tr id=".$id.'">
          <td>'.$id.'</td>
          <td'.$class.'>'.$birthday.'</td>  //<-- apply class
        </tr>';
    }

And css

.font_red{
  color: red;
  }
  • Related