简体   繁体   English

我如何以相反的顺序显示mySql数据

[英]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? 如何准确地以相反的顺序显示表中的信息(使用PHP)?

For example lets say I have a table with an AUTO_INCREMENT id column as primary key and a name column: 例如,假设我有一个表,该表具有一个AUTO_INCREMENT id列作为主键和一个name列:

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

I need to show it in the page like this: 我需要在这样的页面中显示它:

id: 4 Name: Lian id:4名:Lian
id: 3 Name: Bob id:3名称:Bob
id: 2 Name: Elen id:2名称:Elen
id: 1 Name: Cris id:1名: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. PS:我使用$result$rows来计数我有多少行,并尝试在for函数中使用它,但是它没有用。

<?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. 它也有一点HTML,只是用于创建一个显示帖子链接的区域,它最多显示12个博客链接(同一行中有3个帖子,然后跳至下一行),如果博客帖子为太大(超过90像素)时,它会用点覆盖链接(标题)的其余部分。

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 您可以在这里了解ORDER BY ... DESC

You can use array_reverse() function after getting your data to your data structure. 将数据放入数据结构后,可以使用array_reverse()函数。 Here is an implementation of array_reverse function: 这是array_reverse函数的实现:

<?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 有关更多信息,请访问链接: http : //www.w3schools.com/php/func_array_reverse.asp

Just add an ORDER BY clause to your query. 只需在查询中添加ORDER BY子句即可。

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

MySQL will return the rows in the specified sequence. MySQL将按指定的顺序返回行。 (The DESC keyword indicates that the rows are to be returned in descending order, with the highest values first.) DESC关键字指示将以降序返回行,最高值在前。)

Get rid of for loop and it's contents. 摆脱for循环及其内容。 The while ( fetch ) is the right pattern. while ( fetch )是正确的模式。


NOTE: PHP mysql_ interface is deprecated. 注意:不建议使用PHP mysql_接口。 New development should be using either PDO or mysqli interface. 新开发应使用PDOmysqli接口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何以相反的顺序回显 MySQL 结果? - How to echo MySQL results in inverse order? 如何显示MySQL数据库中的数据获取次数? - How do I show number of fetching of a data in a MySQL data base? 如何将每日数据存储到MySQL并以图形形式显示? - How do I store daily data to MySQL and show it in graph? MySQL数据由php显示。 如果选择则显示所选数据,如果不选择则显示; 显示整个数据。 我怎样才能做到这一点? - MySQL Data show by php. If select show selected data, If no select; show whole data. How can I do this? 我如何在wp admin的woocomerce订单详细信息页面上显示自定义用户数据 - How do i show custom user data on the woocomerce order details page in wp admin 如何在屏幕上显示此mysql错误 - How do I show this mysql error on screen 如何按照唯一且预定的顺序(而不是asc或desc)对来自mysql数据库的数据进行排序 - How do I sort data from a mysql db according to a unique and predetermined order, NOT asc or desc 我如何使用计算值对数组排序,其余数据是从mysql数据库接收的? - How do I order an array using a calculated value, where the rest of the data is received from mysql database? 如何使用php以特定顺序显示从mysql db检索到的数据 - How do I display data retrieved from mysql db in a specific order using php 我如何在MySQL的单行中按降序显示出生年份的前端数据 - How do i display data in front-end in descending order for year born given in a single row of mysql
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM