3

Loop SQL rows and sort them

 2 years ago
source link: https://www.codesd.com/item/loop-sql-rows-and-sort-them.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

As it was pointed out in the answers, I was not looking to organize results, but to filter them. I'm sorry for the confusion! :D

I've tried my best to google my way out of this problem, but I'm having a very hard time finding a solution..

I have a SQL database with this structure, as I'm trying to make a basic CMS:

pageid | title | pagetext | menu_par

What I want to do is make a navigation on the page, that loops all the rows and makes them look like links, which my teacher helped me with a few months back:

$query_MenuItems = "SELECT pageid,title,menu_par FROM v2 ORDER BY menu_par ASC";
$MenuItems = $mysqli->query($query_MenuItems);
$row_MenuItem = $MenuItems->fetch_assoc();
$totalRows_MenuItems = $MenuItems->num_rows;    

do { echo
"<a href=\"?page={$row_MenuItem['pageid']}\">{$row_MenuItem['title']}</a><br/>";
}
while ($row_MenuItem = $MenuItems->fetch_assoc());
}

This works fine, however my issue is that I have no idea how to sort the different links, based on what their menu_par value is.

I feel like I have tried everything in my power to fix this, and it is stressing me out

Is there any way I can make a similiar loop as the one above, but sorting it by using more than one?:

while ($row_MenuItem = $MenuItems->fetch_assoc())
{
if ("{$row_MenuItem['menu_par']}" == '1') echo
"<a href=\"?page={$row_MenuItem['id']}\">{$row_MenuItem['title']}</a><br/>";
}

I hope you guys can help me :)


Why not using ORDER BY in Your SQL query?

SELECT pageid,title,menu_par FROM v2 ORDER BY menu_par ASC

By this query (and the ORDER BY x ASC clause) the records are ordered by menu_par value in ascending order...

You can read more about this here: http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html

If You want to filter the results instead depending on the menu_par value (e.g. You want to select just those links that has menu_par == 1) You would use a WHERE clause:

SELECT pageid,title,menu_par FROM v2 WHERE menu_par = 1




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK