简体   繁体   中英

How do i show mySql data in inverse order

Update: thanks for the help everyone, the entire code is on the bottom of the text, with brazilian-portuguese comentary.

How exactly do I show the information I have in my tables (using PHP) in reverse order?

For example lets say I have a table with an AUTO_INCREMENT id column as primary key and a name column:

id: 1 Name: Cris
id: 2 Name: Elen
id: 3 Name: Bob
id: 4 Name: Lian

I need to show it in the page like this:

id: 4 Name: Lian
id: 3 Name: Bob
id: 2 Name: Elen
id: 1 Name: Cris

This code only shows them in normal order, so far it works but it isn't exactly what i need.

PS: I used $result and $rows to count how many rows I had and tried to use it in the for function but it didn't work.

<?php 
    $conect = mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("Noticias", $conect) or die(mysql_error());

    $result = mysql_query("SELECT * FROM titulos", $conect);
    $totalrows = mysql_num_rows($result);

    echo "$totalrows Rows test edit<br>";

    while($row = mysql_fetch_array($result)) {
    echo $row['Titulo'];
    echo "<br>";
    }
    for($i=$totalrows;$i>=0;$i-1){
       $_Str ="SELECT Titulo FROM titulos WHERE id_Noticia=".$i."";
       $show = mysql_query($_Str, $conect);
       echo $show['Titulo']."<br>";
    }
?>

Ok, you guys solved my problem so it's only fair to show what i was trying to do.

I was trying to get the reverse order because i was wanted to create(as an exercise) a page that saves a blog title and its content.

i needed it to show the blog posts in reverse order so the user can see them from newest to oldest.

i also had to make every blog title to be used as a link to the blog post(right now it only gives a reference to the exacly same link, i'm working on it)

it also has a bit of HTML just to create a area where the posts links will be shown, it shows a max of 12 blog links(3 posts in the same line, then it jumps to the next line) and if a blog post is too big(more than 90px) it covers the rest of the link (title) with dots.

again, sorry for bad english, i'm out of practice.

 <?php
 //coneção com o banco de dados onde os dados das nopticias estão salvos
 $conect = mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("Noticias", $conect) or die(mysql_error());

    //Calcula quantas noticias existem salvas no banco de dados, pdoe ser usado 
    //quando o usuario quiser ver todas as noticias
    $result = mysql_query("SELECT * FROM titulos", $conect);
    $totalrows = mysql_num_rows($result);

    //ordena as noticias em ordem decrecente(da mais nova para a mais velha)
    //e salva em um array
    $result2 = mysql_query("SELECT * FROM titulos ORDER BY id_Noticia DESC", $conect);
    $lista = array(); 
    while($row= mysql_fetch_array($result2)) {
    $lista[].=$row['Titulo'];
    }
    //variaveis para manipular quantas noticias aparecerão
    $a=0;
    $b=0;
   ?>
   <html>
    <head>
    <title>Painel de Noticias!!!</title>
    <style>
        //cria a area onde os titulos aparecerão
        .boxed {
        border: 2px solid green ;
        width: 300px;

        }
        //encobre com pontos qualquer parte do titulo que ultrapasse mais de 90 pixels
        .espaco90 {
        width: 90px; 
        float: left;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        }
        </style>
         </head>
         <body>

          <div class="boxed" >
           <p>
            <?php
             //seleciona os titulos e aplica um link para eles, aqui falta um meio de determinar os links para cada
      //titulo existente no banco de dados, más como isso 
       //será usado em conjunto com o wolrd press então eu creio 
       //que não seja necessário aha não ser que você queira
         for($i=0;$i<=$totalrows-1;$i++){
        echo "<div class='espaco90'><a href='http://www.w3schools.com'>".$lista[$i]."</a></div></p><p>";

        $a=$a+1;
        $b=$b+1;
        if($b<12){
        if($a>=3){
            echo "<br>";
            $a=$a-3;
        }
        }else{
            echo"<br>";
            break;
        }
        }
        ?> </p>
        </div>

        </body>
       </html>

This should get items in reverse order

$_Str ="SELECT Titulo FROM titulos WHERE ORDER BY id_Noticia DESC "; 
$show = mysql_query($_Str, $conect); 
for($i=0; $i<$totalrows; $i+1) { 
    echo $show[i]['Titulo']."<br>";
}

Try this:

$result = mysql_query("SELECT * FROM titulos ORDER BY id_Noticia DESC", $conect);

You can learn about ORDER BY ... DESC here

You can use array_reverse() function after getting your data to your data structure. Here is an implementation of array_reverse function:

<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
print_r(array_reverse($a));
?>

For more info visit the link: http://www.w3schools.com/php/func_array_reverse.asp

Just add an ORDER BY clause to your query.

SELECT * FROM titulos ORDER BY id_Noticia DESC
                      ^^^^^^^^^^^^^^^^^^^^^^^^

MySQL will return the rows in the specified sequence. (The DESC keyword indicates that the rows are to be returned in descending order, with the highest values first.)

Get rid of for loop and it's contents. The while ( fetch ) is the right pattern.


NOTE: PHP mysql_ interface is deprecated. New development should be using either PDO or mysqli interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM