...

View Full Version : How can I reverse the data order in this script ?



jeddi
02-15-2010, 09:34 AM
Hi,
I have an interesting problem !

What I am trying to do is to get the last 60 rows of data from my table
and then process them in data order. Sounds easy ...

The column "mday_no" is the day number of the row

So I have used the following this code to put the data in reverse order (by date) so that that I can pick out the last 60 days.


$sql_graph = "SELECT mcb_date, data1, data2, data3 FROM my_tab WHERE prod = '$Db_prod' ORDER BY mday_no DESC LIMIT 60";

$result_graph = mysql_query($sql_graph) or die("could not execute SELECT my_tab". mysql_error());


Now that should get the correct data
- but I actually want to process this data in day order going from
low to high because I am going to use it in a graph.

My script continues to process the data with:


$ctr = 1;
while( $row_graph = mysql_fetch_assoc($result_graph)) {
if( $ctr == 1) {$first_dt = date('d-M-Y', $row_graph['mcb_date']);} // picks out the first date
$data1[] = $row_graph['data1'];
$data2[] = $row_graph['data2'];
$data3[] = $row_graph['data3'];
$ctr++;
}
}

So does anyone know how I can reverse the data after I have selected it ?

At the moment the data runs backwards and "$ctr == 1" is going to be the last date not the first.

Any ideas ?




.

iLochie
02-15-2010, 09:43 AM
I believe what you need is array_reverse. (http://php.net/array_reverse) *I just glanced at the code so I could be wrong..

jeddi
02-15-2010, 10:39 AM
Thanks.

That sounds logical !

So I guess I get my array first with
the select,
then get the row array,
and then reverse it,
and then do the while loop ?

So:


$sql_graph = "SELECT mcb_date, data1, data2, data3 FROM my_tab WHERE prod = '$Db_prod' ORDER BY mday_no DESC LIMIT 60";

$result_graph = mysql_query($sql_graph) or die("could not execute SELECT my_tab". mysql_error());

$row_graph = mysql_fetch_assoc($result_graph);

$row_graph = array_reverse($row_graph);

$ctr = 1;
while( $row_graph) {
if( $ctr == 1) {$first_dt = date('d-M-Y', $row_graph['mcb_date']);} // picks out the first date
$data1[] = $row_graph['data1'];
$data2[] = $row_graph['data2'];
$data3[] = $row_graph['data3'];
$ctr++;
}
}

Does that look about right ?




.

koko5
02-15-2010, 10:58 AM
$sql_graph = "SELECT * FROM
(SELECT mcb_date, data1, data2, data3 FROM my_tab
WHERE prod = '$Db_prod' ORDER BY mday_no DESC LIMIT 60) A
ORDER BY mday_no ASC";:thumbsup:

jeddi
02-15-2010, 11:33 AM
Hmm .. thats interesting !

what is that first A in "A ORDER BY mday_no ASC" ?

haven't seen that before !




.

koko5
02-15-2010, 11:57 AM
Hmm .. thats interesting !

what is that first A in "A ORDER BY mday_no ASC" ?

haven't seen that before !




.

It's derived table alias :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum