问题
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:
- Sort your links descending
- 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