How to do ascending and descending listing in records with PHP

4

My table looks like this

ThroughPHP,IamlistingMYSQLdatabaserecordswithinaWHILELOOP.
Iwouldliketoknowhowtodothissothat,byclickingonID,or,DATA,thedatawillbedisplayedinascendingordescendingorder.

SCRIPTPHP:

<?php$strSQL="SELECT * FROM TABELA ORDER BY id DESC";
$rs = mysqli_query($conecta,$strSQL); 
$error = mysqli_error($conecta);
if(!$error){
while($row = mysqli_fetch_array($rs)):
?>
<ul class="lista-posts">       
   <li class="seleciona"><input type="checkbox" id="checkbox" name="deletar[]" value="<?php echo $row['id']; ?> " /></li>
    <li class="id"><?php echo $row['id']; ?></li>
    <li class="titulo"><?php echo '<a title="'.$row['titulo'].'" class="link-texto" href="artigo-'.$row['slug'].'">'.substr($row['titulo'], 0, 63).'</a>'; ?></li>
    <li class="data"><?php echo '<data class="data">'.date('d/m/Y', strtotime($row['data'])).'</data>'; ?></li>
    <li class="data"><?php     
    if($row['id_categoria'] == 'faq') {
        $novoIdCategoria = str_replace("faq","duvidas-frequentes",$row['id_categoria']);
        echo '<a href="'.$novoIdCategoria.'.php">'.ucfirst("faq").'</a></data>'; 
    } else {
        echo '<a href="'.$row['id_categoria'].'.php">'.ucfirst($row['id_categoria']).'</a></data>'; 
    } ?></li>        
    <li class="gerenciar"><?php 
        echo '<a title="Ver" class="apagar" href="artigo-'.$row['slug'].'"><label class="icon-eye"></label></a>';
        echo '<a title="Editar" class="editar" href="edita.php?id='.$row['id'].'"><label class=" icon-pencil"></label></a>';?>         
    </li> 
</ul>    
<?php endwhile; ?>

Thank you in advance!

    
asked by anonymous 18.12.2015 / 19:26

1 answer

4

You will need to run your query again on the click by changing the field and the orientation of the ordering example:

$strSQL = "SELECT * FROM TABELA ORDER BY id DESC";

$strSQL = "SELECT * FROM TABELA ORDER BY id ASC";

Another field:

$strSQL = "SELECT * FROM TABELA ORDER BY outrocampo DESC";

Updating with a more complete way to do:

On the left side of the link, place an up and down arrow on the right side of the link.

THE ARROWS WILL BE A LINK THAT POINTS TO THE SAME PAGE, BUT WITH PARAMETERS YOU WILL USE IN THE SELECT.

<a href="mesma_pagina.php?ordem=crescente&campo=data"> <img src="setapracima.png" /> </a>
 Data
<a href="mesma_pagina.php?ordem=decrescente&campo=data"> <img src="setaprabaixo.png" /> </a>

When you click up, you will put in ascending order your Select ie ASC So. will look like this:

   if($_GET['ordem] == "crescente")
      $sql = 'select * from tabela order by '.$_GET['campo'].' asc'; # na verdade nem precisa por asc
   elseif($_GET['ordem'] == "decrescente")
      $sql = 'select * from tabela order by '.$_GET['campo'].' desc'; # precisa por desc
   else
      $sql = 'select * from tabela'; # vai entrar aqui da primeira vez que carregar a página.

$exe = mysql_query($sql);
    
18.12.2015 / 19:30