Organize HTML table data - CSS - SQL

Asked

Viewed 523 times

0

I have the following code

<table border="1">
<?php
$sql = $mysql->prepare("SELECT id FROM usuarios WHERE status = 0");
$sql->execute();
$sql->bind_result($id);
$sql->store_result();
if($sql->num_rows() == 0){
	echo "<tr><td>Sem registros</td></tr>";
} else {
	while ($sql->fetch()) { 
		echo "<tr>
		<td>" . $id . "</td>
		</tr>";
	}
}
?>
</table>

Which brings me back 30 records lined up from top to bottom, as follows:

pagina_1

I need to sort the results in an increasing way, but organized in other columns, so that it looks like this:

pagina_2

How to proceed in this case?

  • A link that might help you: https://stackoverflow.com/questions/17608513/loop-to-populate-html-table-vertically

  • With CSS and the "column-Count" property you can easily assemble this structure.

  • 2

    Hello friend. Managed to solve? see that I posted a solution using Javascript, but someone found it useless and voted negative. If you couldn’t solve it, we can see a solution using only PHP. Just give me a feedback there. Obg!

1 answer

0


My suggestion is to use Javascript to change the structure by inserting the cells into the lines. In PHP you can insert classes by numbering lines in sequence, from 1 to 10. The table structure would look like the image below, each row in a sequence of linha1 to linha10:

inserir a descrição da imagem aqui

From this, with Javascript I can join all cells of the lines with the same class. Just insert a script right after the PHP code that builds the table:

<?php
$sql = $mysql->prepare("SELECT id FROM usuarios WHERE status = 0");
$sql->execute();
$sql->bind_result($id);
$sql->store_result();
if($sql->num_rows() == 0){
    echo "<tr><td>Sem registros</td></tr>";
} else {
   $conta = 1; // inicia variável com valor 1
    while ($sql->fetch()) { 

      if($conta%11 == 0){ // reseta $conta a cada 11 linhas
         $conta = 1;
      }

      $classe = "linha".$conta;

        echo "<tr class=". $classe ."> // insere a classe na TR
        <td>" . $id . "</td>
        </tr>";

      $conta++;

    }
}
?>
</table>

<script>
var linhas = document.body.querySelectorAll("tr[class*='linha']"); //seleciona todas as linhas da tabela
for(var x=10; x<linhas.length; x++){ // loop a partir da 11ª linha
   var cls = linhas[x].className.match(/\d+/)[0]; // pega o número da linha
   document.querySelector(".linha"+cls).innerHTML += linhas[x].innerHTML; // insere a TD na respectiva linha
   linhas[x].outerHTML = ''; // remove a linha
}
</script>

The result will be what shows the figure below:

inserir a descrição da imagem aqui

Browser other questions tagged

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