Change the color of a cell according to the value

Asked

Viewed 1,174 times

2

I have a page with a table that shows information on the number of items expected to be performed and the number of items that were actually performed at the end of each month.

inserir a descrição da imagem aqui

I was asked that, in case the month has more items performed than predicted, the cell that shows the amount performed be green and otherwise, red.

inserir a descrição da imagem aqui I have no idea the possibility of doing this, but if anyone knows how to do it, please comment here.

The code of the table:

<!-- Main -->
        <div class="content-lg container">
            <div class="row margin-b-20">
                <div class="col-sm-6">
                    <h2>Prev x Real Month</h2>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-12 sm-margin-b-50">

                    <script type="text/javascript">
                        //Pegar o ID do botão clicado 
                        function abreModal (idR)
                        {
                            $.post("/Teste_Obeya/ajax.php", 
                            { id : idR }, function(content){
                                $(".modal-body").html(content); 
                            }, 'html');
                        }
                    </script>


                            <?php

                            require 'conn.php';

                            //Conexão e consulta ao Mysql
                            $qry = mysqli_query($lnk, "select * from qualite");

                            //Pegando os nomes dos campos
                            $num_fields = mysqli_num_fields($qry);//Obtém o número de campos do resultado

                            for($i = 0;$i<$num_fields; $i++){//Pega o nome dos campos
                                $fields[] = mysqli_fetch_field_direct($qry,$i)->name;
                            }

                            //Montando o cabeçalho da tabela
                            $table = '<table  class="table table-hover table-inverse"> <tr style="">';

                            for($i = 0;$i < $num_fields; $i++){
                                $table .= '<th style="padding-right:5px;">'.$fields[$i].'</th>';
                            }

                            //Montando o corpo da tabela
                            $table .= '<tbody >';
                            while($r = mysqli_fetch_array($qry)){
                                $table .= '<tr>';
                                for($i = 0;$i < $num_fields; $i++){
                                    $table .= '<td>'.$r[$fields[$i]].'</td>';
                                }

                                // Adicionando botão de edição

                                $table .= '<td><form action="qualite-edicao.php" method="post">'; 
                                $table .= '<input type="hidden" name="ID" value="'.$r['ID'].'">';
                                $table .= '<input type="hidden" name="KPI" value="'.$r['KPI'].'">';
                                $table .= '<input type="hidden" name="PILOTE" value="'.$r['PILOTE'].'">';
                                $table .= '<input type="hidden" name="JAN PREV" value="'.$r['JAN_PREV'].'">';
                                $table .= '<input type="hidden" name="JAN REAL" value="'.$r['JAN_REAL'].'">';
                                $table .= '<input type="hidden" name="FEV PREV" value="'.$r['FEV_PREV'].'">';
                                $table .= '<input type="hidden" name="FEV REAL" value="'.$r['FEV_REAL'].'">';
                                $table .= '<input type="hidden" name="MAR PREV" value="'.$r['MAR_PREV'].'">';
                                $table .= '<input type="hidden" name="MAR REAL" value="'.$r['MAR_REAL'].'">';
                                $table .= '<input type="hidden" name="ABR PREV" value="'.$r['ABR_PREV'].'">';
                                $table .= '<input type="hidden" name="ABR REAL" value="'.$r['ABR_REAL'].'">';
                                $table .= '<input type="hidden" name="MAI PREV" value="'.$r['MAI_PREV'].'">';
                                $table .= '<input type="hidden" name="MAI REAL" value="'.$r['MAI_REAL'].'">';
                                $table .= '<input type="hidden" name="JUN PREV" value="'.$r['JUN_PREV'].'">';
                                $table .= '<input type="hidden" name="JUN REAL" value="'.$r['JUN_REAL'].'">';
                                $table .= '<input type="hidden" name="JUL PREV" value="'.$r['JUL_PREV'].'">';
                                $table .= '<input type="hidden" name="JUL REAL" value="'.$r['JUL_REAL'].'">';
                                $table .= '<input type="hidden" name="AGO PREV" value="'.$r['AGO_PREV'].'">';
                                $table .= '<input type="hidden" name="AGO REAL" value="'.$r['AGO_REAL'].'">';
                                $table .= '<input type="hidden" name="SET PREV" value="'.$r['SET_PREV'].'">';
                                $table .= '<input type="hidden" name="SET REAL" value="'.$r['SET_REAL'].'">';
                                $table .= '<input type="hidden" name="OUT PREV" value="'.$r['OUT_PREV'].'">';
                                $table .= '<input type="hidden" name="OUT REAL" value="'.$r['OUT_REAL'].'">';
                                $table .= '<input type="hidden" name="NOV PREV" value="'.$r['NOV_PREV'].'">';
                                $table .= '<input type="hidden" name="NOV REAL" value="'.$r['NOV_REAL'].'">';
                                $table .= '<input type="hidden" name="DEZ PREV" value="'.$r['DEZ_PREV'].'">';
                                $table .= '<input type="hidden" name="DEZ REAL" value="'.$r['DEZ_REAL'].'">';
                                $table .= '<button class="btn btn-primary"><i class="fa fa-calendar-o" aria-hidden="true"></i></i> Editar </i></button>'; //
                                $table .= '</form></td>';



                                //MODAL COM O GRÁFICO
                                $table .= '<td><form action="graf-qualite.php" method="post">'; 
                                $table .= '<input type="hidden" name="ID" value="'.$r['ID'].'">';
                                $table .= '<input type="hidden" name="KPI" value="'.$r['KPI'].'">';
                                $table .= '<input type="hidden" name="PILOTE" value="'.$r['PILOTE'].'">';
                                $table .= '<input type="hidden" name="JAN PREV" value="'.$r['JAN PREV'].'">';
                                $table .= '<input type="hidden" name="JAN REAL" value="'.$r['JAN REAL'].'">';
                                $table .= '<input type="hidden" name="FEV PREV" value="'.$r['FEV PREV'].'">';
                                $table .= '<input type="hidden" name="FEV REAL" value="'.$r['FEV REAL'].'">';
                                $table .= '<input type="hidden" name="MAR PREV" value="'.$r['MAR PREV'].'">';
                                $table .= '<input type="hidden" name="MAR REAL" value="'.$r['MAR REAL'].'">';
                                $table .= '<input type="hidden" name="ABR PREV" value="'.$r['ABR PREV'].'">';
                                $table .= '<input type="hidden" name="ABR REAL" value="'.$r['ABR REAL'].'">';
                                $table .= '<input type="hidden" name="MAI PREV" value="'.$r['MAI PREV'].'">';
                                $table .= '<input type="hidden" name="MAI REAL" value="'.$r['MAI REAL'].'">';
                                $table .= '<input type="hidden" name="JUN PREV" value="'.$r['JUN PREV'].'">';
                                $table .= '<input type="hidden" name="JUN REAL" value="'.$r['JUN REAL'].'">';
                                $table .= '<input type="hidden" name="JUL PREV" value="'.$r['JUL PREV'].'">';
                                $table .= '<input type="hidden" name="JUL REAL" value="'.$r['JUL REAL'].'">';
                                $table .= '<input type="hidden" name="AGO PREV" value="'.$r['AGO PREV'].'">';
                                $table .= '<input type="hidden" name="AGO REAL" value="'.$r['AGO REAL'].'">';
                                $table .= '<input type="hidden" name="SET PREV" value="'.$r['SET PREV'].'">';
                                $table .= '<input type="hidden" name="SET REAL" value="'.$r['SET REAL'].'">';
                                $table .= '<input type="hidden" name="OUT PREV" value="'.$r['OUT PREV'].'">';
                                $table .= '<input type="hidden" name="OUT REAL" value="'.$r['OUT REAL'].'">';
                                $table .= '<input type="hidden" name="NOV PREV" value="'.$r['NOV PREV'].'">';
                                $table .= '<input type="hidden" name="NOV REAL" value="'.$r['NOV REAL'].'">';
                                $table .= '<input type="hidden" name="DEZ PREV" value="'.$r['DEZ PREV'].'">';
                                $table .= '<input type="hidden" name="DEZ REAL" value="'.$r['DEZ REAL'].'">';
                                $table .= '<!-- Button -->
                                            <button type="button" class="btn btn-info button" data-toggle="modal" data-target="#exampleModal" name="button" onclick="abreModal(' . $r['ID'] .');">
                                              Gráfico
                                            </button>

                                            <!-- Modal -->

                                            <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" onload="click("button");">
                                              <div class="modal-dialog" role="document">
                                                <div class="modal-content">
                                                  <div class="modal-header">
                                                    <h5 class="modal-title" id="exampleModalLabel">Gráfico</h5>
                                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                      <span aria-hidden="true">&times;</span>
                                                    </button>
                                                    </div>
                                                    <div class="modal-body">


                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                                    </div>
                                                </div>
                                              </div>
                                            </div>'; //
                                $table .= '</form></td>';

                            }

                            //Finalizando a tabela
                            $table .= '</tbody></table>';


                            //Imprimindo a tabela
                            echo '<div class="table-table" style="overflow-x:auto;">';
                            echo $table;
                    ?>

                    </div>
                </div>
            </div>
        </div>

This is the bank:

inserir a descrição da imagem aqui

  • 1

    Mariana, you need to specify better how your project works, whether it’s in php submitting html responses to the browser, or whether it works with javascript and ajax making requests to the server and returning responses in json or xml. In your question did not show any piece of code of your project. Complicated provide you paths to problem solving.

  • Oops, I forgot to put the code. I’m sorry, I really forgot.

2 answers

2


I’ll have to invent names to help you because you didn’t post the sql code as the column names that return the database values.

So I see your bow While Answer with the line numbers corresponding to your query in the database while loop FOR read field the field returned from the query. Remove the FOR loop and just do the while using the column name in the code itself as below:

//Montando o corpo da tabela
$table .= '<tbody >';
while($r = mysqli_fetch_array($qry)){
    $table .= '<tr>';
    for($i = 0;$i < $num_fields; $i++){
        $table .= '<td>'.$r[$fields[$i]].'</td>';
    }
}

Inside your loop is where it prints the output of each ballot you have the variable $r. Correct ?

porting to color the output, say the desired monthly value attribute is a column in your table qualite which we shall call here Mensalpretendido and the value achieved is a column named here Mensalalcancado.

you could change your code and do that:

while($r = mysqli_fetch_array($qry)){
    $table .= '<tr>';
    if($r['MensalPretendido'] > $r['MensalAlcancado']){
      $table .= '<td style="background:red;">'.$r['MensalPretendido'].'</td>';
      $table .= '<td style="background:red;">'.$r['MensalAlcancado'].'</td>';
    }else{
      $table .= '<td style="background:green;">'.$r['MensagemPretendido'].'</td>';
      $table .= '<td style="background:green;">'.$r['MensalAlcancado'].'</td>';
    }
    //aqui concatena na variavel **$table** outras colunas da tabela se 
    //houver....
}

That is; if the column value Mensalpretendido is greater than the value of Mensalalcancado prints the ballot in red otherwise prints in green.

Through what happened I tried to return the answer in an easy way of understanding but did not have the names of the fields to rewrite the code then adapt to your project.

Updating

All answers provided here are based on understanding logic, both my answer and the magnific Ricardo Pontual has been provided the completely correct logic of achieving the desired result! Now if you want to copy and paste without having to understand and debug your code you will need to pass full access to your entire environment so that we have the same understanding of the person who modeled the code.

First you need to set up your programming environment to display errors and warnings, this is done by changing a directive within your php.ini call display_errors for ON or at the top of your php page use

<?php
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
?>

otherwise it is difficult to understand what is happening. I would very much like one of the two answers to help you.

  • First: Thank you for answering! Second: I tried to use your code by 'JAN_PREV' and 'JAN_REAL' which are the January columns, for example, but the page stopped working.

  • 1

    Update your question and post the code you entered and the error you gave please? leverages and adds the sql fields of your table to understand the schema as it was mounted!

  • So I put the bank in question. I literally copied your code and just changed the name of the columns, but it says "This page is not working".

  • @Marianaferreira In the logic that Rafael proposes, you need to use the column name instead of the index. He put as example "Mensalpretendido" but you need to see the exact table in the bank. You mentioned that it is "JAN_PREV", and the example is for the beginning of the table, you need to repeat the code and treat the other columns, as I imagine "FEV_PREV" and so on, otherwise it will not work, take advantage of the idea of logic and try to adapt, do only with one column initially and then add the other months

  • 1

    So I fixed some things and adapted them to what I needed. I’m going to do an Edit showing the result and the code. Thank you both.

2

It would be simple to compare on the line you generate to td, but you’re doing it in a for dynamically, using an index and not field names, which makes it difficult.
Looking at its code, we can see that the first column with the "predicted" value is the fourth, if we think of the index of the array, index 3 and the real index 4.

We can then use the following logic: "If the index column is odd, from 3a the predicted value, and if even the actual value"
Then you can create two variables, one for the predicted value and the other for the real, save their respective values according to the index (even or odd), in your case the variable $i, and assign a class in the TD according to the background color you want.

First, add to your CSS two classes, for example like this:

.fundoVerde {
   background-color: green;
   color: #fff
}
.fundoVermelho {
   background-color: red;
   color: #fff
}

Then in the for that generates the columns, implement the logic I proposed above:

$nomeClasse = 'class=""';
$prev = 0;
$real = 0;
for($i = 0;$i < $num_fields; $i++){
   if ($i >= 3) {
      // Se par
      if ($i % 2 == 0) {
         $real = $r[$fields[$i]];
         if ($real > $prev) {
            $nomeClasse = 'class="fundoVerde"'
         else
            $nomeClasse = 'class="fundoVermelho"';
         }
      } else {
         // se ímpar
         $nomeClasse = 'class=""';
         $prev = $r[$fields[$i]];
      }
   }
   // concatena a classe
   $table .= '<td '.$nomeClasse.'>'.$r[$fields[$i]].'</td>';
}

The logic is this, may need to convert the value to compare or some small adjustment.

  • So I used your code and I just changed a {} and ; but the header didn’t show up, only a little red box came up instead. I will edit showing the result.

  • 1

    Well, this code is under the header, so it’s weird that it doesn’t show up, you have to look at the html that was generated to understand. See also that, regardless of the logic I proposed, will always be inserted td normally, so I can’t see where you might not be showing the columns, I suggest you take a look at the html and see what’s missing

Browser other questions tagged

You are not signed in. Login or sign up in order to post.