Change color column date in mysql and php

1

I have a field in a table in my DB that is called fehca, my question is how can I make it show in my php statement change color depending on the condition of the date, for example If 14 days have passed since the date the color shown will be red if it's been 8 days it should be yellow if 5 days have passed it should be green

I want the date field to be shown in other colors depending on the condition, I do not know how you could do that

  $alumnos="SELECT * FROM contribuyente $where $limit";
  $resAlumnos=$conexion->query($alumnos);
  $resCarreras=$conexion->query($alumnos);

  if(mysqli_num_rows($resAlumnos)==0)
  {
  $mensaje="<h1>No hay registros que coincidan con su criterio de búsqueda.</h1>";
   }
   ?>

  <?php include 'partials/menu.php';?>
  <div class="container">
   <div class="starter-template">
    <br>
    <br>
    <br>
    <div class="jumbotron">
        <div class="container text-center">
            <h2><strong>Bienvenido</strong> <?php echo $_SESSION["usuario"]["nombre"]; ?></h2>
            <p>Panel de control | <span class="label label-info"><?php echo $_SESSION["usuario"]["privilegio"] == 1 ? 'Admin' : 'Cliente'; ?></span></p>
            <p>
                <a href="cerrar-sesion.php" class="btn btn-primary btn-lg">Cerrar sesión</a>
            </p>
        </div>
    </div>
  </div>
  </div><!-- /.container -->
  <?php include 'partials/footer.php';?>
  <section class="box"> 
        <form method="post">
            <input type="text" placeholder="Folio" name="nombre"/>

            <button name="buscar" type="submit" class="button special icon fa-search ">Buscar</button>
                  ";
        </form></section>
    <div class="panel panel-default">
                <div class="panel-body">
    <table class="table">
            <tr class="odd gradeX">
                <th>Folio</th>
                <th>Nombre</th>
                <th>Rut</th>
                <th>Correo</th>
                <th>Telefono</th>
                <th>Direccion</th>
                <th>Poste</th>
                <th>Solicitud</th>
                <th>Fecha</th>
                <th>Estado</th>
                <th>Borrar</th>
                <th>Reporte</th>
                <th>Enviar</th>

            </tr>

            <?php

            while ($registro = $resAlumnos->fetch_array(MYSQLI_BOTH))
            {

                    echo "<tr class='success'>";
                   echo "<form action ='guardar.php' method= 'POST'>";
                    echo "<td>$registro[0]</td>";
                    echo "<td>$registro[1]</td>";
                    echo "<td>$registro[2]</td>";
                    echo "<td>$registro[3]</td>";
                    echo "<td>$registro[4]</td>";
                    echo "<td>$registro[5]</td>";
                    echo "<td>$registro[6]</td>";
                    echo "<td>$registro[7]</td>";
                    echo "<td>$registro[10]</td>";
                    echo "<td>$registro[8]</td>";
                    echo "<td><a href='admin.php?id=$registro[0]&idborrar=2'><img src='./images/eliminar.png' class='img-rounded'/></a></td>";
                    echo "<ul class='actions'>";
                    echo "<td><a href='actualizar.php?id=$registro[0]'><img src='./images/editar.png' class='img-rounded'></td>";
                    echo "<td><a href='enviarmail.php?id=$registro[0]'><img src='./images/enviar.png' class='img-rounded'></td>";
                    echo "</ul>";
                    echo "</form>";



                echo "</tr>";
             }

            echo "</table>";
    
asked by Daniela 22.05.2018 в 23:38
source

2 answers

1

I propose a solution from PHP. There when creating the table you will send the date to a function that will compare the days elapsed between that date and the current date (or any other date you want) and based on that will assign the date value a CSS class with the color.

Then, via CSS, you will apply the color.

I'll show you a complete example.

PHP Code

EDIT: Optimized version, we dispense with switch , looking for the color value in an array based on the number of days. We gain clarity and code writing, especially in case of having to evaluate many options.

I have simulated an array with your data, from which the table is built.

<?php

    /*Datos desde donde se construye la tabla*/
    $arrDatos=array(
                        array("folio"=>155, "nombre"=>"Juana", "fecha"=>"2018-05-09"),
                        array("folio"=>156, "nombre"=>"Luisa", "fecha"=>"2018-05-15"),
                        array("folio"=>157, "nombre"=>"Daniela", "fecha"=>"2018-05-18"),
                        array("folio"=>158, "nombre"=>"Camila", "fecha"=>"2018-05-22"),
                );

    /*Vamos a crear una variable a la cual le iremos concatenando los elementos de la tabla*/
    $tableHTML='<table class="my-table">';
    /*Obtenemos encabezados de forma dinámica*/
    $arrHeaders=array_keys($arrDatos[0]);
    $tableHeaders= '<thead><th>'.implode('</th><th>', $arrHeaders).'</th></thead>';
    $tableHTML.=$tableHeaders;

    foreach ($arrDatos as $items) {
        $tableHTML.='<tr>';    
        foreach ($items as $k=>$v) {
            $td='<td>';
            /*Aquí, cuando sea la clave "fecha", asignaremos el dato evaluando con la función checkDates*/
            $td.=($k=="fecha") ? checkDates($v) : $v;
            $td.='</td>';            
            $tableHTML.=$td;            
        }
        $tableHTML.='</tr>';
    }

    $tableHTML.='</table>';
    echo $tableHTML;


    /*Función para comparar las fechas*/
    function checkDates($strDate){
        $dateThis = new DateTime($strDate);
        $dateToday = new DateTime('now');

        /*
           *Cuando usamos diff obtenemos un objeto en el
           *cual se encuentran, entre otros datos
           *la diferencia en días. La propiedad es days
        */
        $diffDays = $dateToday->diff($dateThis)->days;
        //echo $diffDays.PHP_EOL;

        $arrColors = array('green'=>5, 'yellow'=>8, 'red'=>14);

        $ifColor=array_search($diffDays, $arrColors);
        $cssColor=($ifColor) ? 'color-'.$ifColor : 'color-black';

        return '<span class="'.$cssColor.'">'.$strDate.'</span>'; 
    }
?>

The output of this code will be something like this:

<table class="my-table">
    <thead>
        <tr>
            <th>folio</th>
            <th>nombre</th>
            <th>fecha</th>
        </tr>
    </thead>

    <tr>
        <td>155</td>
        <td>Juana</td>
        <td><span class="color-red">2018-05-09</span></td>
    </tr>

    <tr>
        <td>156</td>
        <td>Luisa</td>
        <td><span class="color-yellow">2018-05-15</span></td>
    </tr>

    <tr>
        <td>157</td>
        <td>Daniela</td>
        <td><span class="color-green">2018-05-18</span></td>
    </tr>

    <tr>
        <td>158</td>
        <td>Camila</td>
        <td><span class="color-black">2018-05-22</span></td>
    </tr>
</table>

CSS Code

The CSS code that sets the color is as simple as this:

.color-yellow {
    color:#ffd500; /*Puede que yellow sea difícil de ver*/
}

.color-green {
    color:green;
}

.color-red {
    color:red;
}

We will see a fragment of code from the output of our table, combined with CSS:

<style>
.my-table {
	border-collapse:collapse;
	width:100%;
}

.my-table td,.my-table th {
	border:0px solid black;
	padding:4px;
}

.my-table tr:nth-child(even) {
	background-color:#f2f2f2;
}

.my-table tr:hover {
	background-color:#ddd;
}

.my-table th {
	padding-top:12px;
	padding-bottom:12px;
	text-align:left;
	background-color:#7f7fff;
	color:#fff;
}

.color-yellow {
	color:#ffd500;
}

.color-green {
	color:green;
}

.color-red {
	color:red;
}
    <table class="my-table">
        <thead>
            <tr>
                <th>folio</th>
                <th>nombre</th>
                <th>fecha</th>
            </tr>
        </thead>

        <tr>
            <td>155</td>
            <td>Juana</td>
            <td><span class="color-red">2018-05-09</span></td>
        </tr>

        <tr>
            <td>156</td>
            <td>Luisa</td>
            <td><span class="color-yellow">2018-05-15</span></td>
        </tr>

        <tr>
            <td>157</td>
            <td>Daniela</td>
            <td><span class="color-green">2018-05-18</span></td>
        </tr>

        <tr>
            <td>158</td>
            <td>Camila</td>
            <td><span class="color-black">2018-05-22</span></td>
        </tr>
    </table>
    
answered by 23.05.2018 в 03:02
0

You can do it with javascript.

1. Get the data with JS where you need it. Normally if you have it in a table you can get it with innerHTML referring to the class of the element.

You have something like that < th class="date" > Firstname < / th >

var x = document.getElementsByClassName("fecha");
  • Try to use the format of the dates in JS link I would recommend that you create a Date object .

  • Make the conditions based on the date object that you created and the object you refer to today. If the conditions are met, you can change the style of your entire row

  • document.TUELEMENTO.style.backgroundColor="red";

        
    answered by 23.05.2018 в 00:48