PHP Reverse the order of results from MySQL DB [duplicate]

ぐ巨炮叔叔 提交于 2021-02-19 06:18:05

问题


I want to reverse the order of the array.

My code:

$result = mysql_query("SELECT * FROM notfi1 WHERE Own='" .$_GET['u']. "'");
while($row = mysql_fetch_array($result))
  {
  echo 'link:<a href=member.php?u=' .$row['UserId']. '>text</a><br>';
  }

Output:

<a href=member.php?u=name8>text</a>
<a href=member.php?u=name9>text</a>
<a href=member.php?u=name10>text</a>

and I want to reverse it:

<a href=member.php?u=name10>text</a>
<a href=member.php?u=name9>text</a>
<a href=member.php?u=name8>text</a>

回答1:


You have two solutions:

  1. Sort your links descending
  2. Use array_reverse or rsort

Solution #1:

"SELECT * FROM notfi1 WHERE Own='" .$_GET['u']. "' ORDER BY UserId DESC"

Solution #2:

$result = mysql_query("SELECT * FROM notfi1 WHERE Own='" .$_GET['u']. "'");
while($row = mysql_fetch_array($result))
{
    $data[] = $row['UserId'];
}
rsort($data);
foreach($data as $item){
    echo 'link:<a href=member.php?u=' .$row['UserId']. '>text</a><br>';
}

Second method is better because it means you are seperating your data retrieval from your display... IT SHOULD be done this way but doesn't prevent you to sort your data on the MySQL Server




回答2:


If you want to show newest ID's first just sorty by user id

$result = mysql_query("SELECT * FROM notfi1 WHERE Own='" .$_GET['u']. "' ORDER BY UserId DESC");
while($row = mysql_fetch_array($result))
{
    echo 'link:<a href=member.php?u=' .$row['UserId']. '>text</a><br>';
}



回答3:


Add an ORDER BY UserId DESC to the SQL and let the database do it for you:

$result = mysql_query("SELECT * FROM notfi1 WHERE Own='" .$_GET['u']. "' ORDER BY UserID DESC");

Side notes:

With that code you'd darn better pray nobody ever goes to yoururl.com/yourpage.php?u='%20OR%201%3D1%20-- or worse. I suggest you read up on SQL injection attacks.

And if this is not old code you're modifying, you shouldn't be using mysql_* functions in the first place. They're deprecated.



来源:https://stackoverflow.com/questions/12842804/php-reverse-the-order-of-results-from-mysql-db

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!