By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,664 Members | 1,656 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,664 IT Pros & Developers. It's quick & easy.

Ordering Problem with PHP and MySQL

P: 5
Hello PHP Peoples! I'm having a bit of a problem, probably simple, but I can't seem to find any info on how to fix it. PHP version is 4.4.7 and MySQL version is 4.0.27.

So here's the problem. Let's say I have 12 rows of data when I grab the rows from the DB with this code:

Expand|Select|Wrap|Line Numbers
  1. $sql = "select * from infop2 order by field_id2";
  2. $result = mysql_query($sql,$connection);
  3. $rows = mysql_num_rows($result);
  4. for ($r = 1; $r <= $rows; $r++) {
  5. $row = mysql_fetch_array($result);
  6. extract($row);
The column "field_id2" is the primary key. Rows 10, 11, and 12 are displayed right after Row 1 instead of Row 9. I've only been working with PHP for about five years but I've made some pretty large scheduling programs and such and I've never encountered this before. Any ideas?

I have been experimenting with this and have discovered that when I create a record with a 20-29 for the "field_id2" value that then displays after row 2.
Feb 22 '08 #1
Share this Question
Share on Google+
3 Replies


P: 5
OK fixed it. Moderators please erase this if you like.
Feb 22 '08 #2

code green
Expert 100+
P: 1,726
By row I take that you mean field_id2.
The actual database table row numbers are meaningless
OK you have ordered by field_id2
Expand|Select|Wrap|Line Numbers
  1. select * from infop2 order by field_id2
And as expected it is returned in a binary order, This is basic computer science.
Expand|Select|Wrap|Line Numbers
  1. 1
  2. 10
  3. 11
  4. 12
  5. 2
  6. 3 etc
PHP has a natural order function that you can use
Expand|Select|Wrap|Line Numbers
  1. bool natsort ( array &array )
  2. This function implements a sort algorithm that orders alphanumeric strings 
  3. in the way a human being would while maintaining key/value associations. 
  4. This is described as a "natural ordering".
Feb 22 '08 #3

P: 5
Sorry, yes by the numbering I was referring to was by the primary key(column field_id2). The problem was solved by switching the data type for the field to integer and then everything feel into place.
Feb 22 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.