Slark
Slark

Reputation: 31

Php foreach from Database in correct order

what could cause the issue that my foreach does not echo the user of my database in the correct order (like the order in my database?

My basic foreach looks like this:

foreach($users as $user) {
     echo $user[username];
}

Upvotes: 0

Views: 87

Answers (3)

user5466402
user5466402

Reputation:

Since we don't have any idea of how your database is made, and also you haven't shown us the query you use to select your data I will try to explain you how to select data in the order you want/need.

Let's suppose your table is MyUsers and contains the following columns:

  • MyUserID
  • Username

If you want to select data ordered by ID just use the following query:

SELECT * FROM MyUsers ORDER BY MyUserID

In the PHP code you will have something like this:

foreach($users as $user) {
   echo $user['Username']; // Ordered by ID
}

If you want to order them by username just:

SELECT * FROM MyUsers ORDER BY Username

PHP will be the same but this time values will be ordered by the username (A-Z).

NOTE: It's always good to use an ORDER BY in queries since we cannot rely on default row order.

For further information, especially if you're new to SQL/MySQL I recommend you to give a look to the following links:

Good luck and I hope this helped you!

Upvotes: 0

Thomas N T
Thomas N T

Reputation: 459

Hope this is the problem with your query.
you try SQL ORDER BY in query. It sorts the records in ascending/descending order by default.

Upvotes: 0

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

change

echo $user[username];

to

echo $user['username'];

You can verify the exact key values using:

 print_r($user);

Upvotes: 1

Related Questions