Looping through columns of a single row query result

The scenario: a table has multiple columns containing the dates for accounting timeframes (column names: at01, at02, at03, etc. and values 2011-01-31, 2011-02-28, etc.) for 12 months (there are actually 13 columns for this though for some reason so it goes at01, at02, … at13).

Since the fiscal year may not match the actual calendar year, it is not always the case where the last two characters of the column name (e.g. at01) will match the current month (01 for January). There are also other columns in the table.

I have to take the returned data from a query limited to one row result (e.g. select * from table limit 1) and use a for loop to see which of the
columns has the needed value. I am currently trying to use a for loop to go through these values which I will compare to the current year, month and day.

The problem I am encountering so far is that the values in the columns are not all returning. Here is my current code:

        $q="select at01,at02,at03,at04,at05,at06,at07,at08,at09,at10,at11,at12,at13 from table limit 1";//I would like to query this as select * instead
        $recCount = count($gl);
echo "<script type=\\"text/javascript\\">alert('".$recCount."')</script>";// This is showing the correct count
        $values = array_values($gl);
        for($i=1; $i < $recCount;$i++) {

                if($i < 10){
                        $at = "0".$i;//if $i is less than 10 need to add a zero to the front of it to match the column name
                } else {
                        $at = $i;
                $value = $values[$at];

echo "<script type=\\"text/javascript\\">alert('at:".$at ." " .$value."')</script>";

The last echo using the alert box appears the correct number of times but it only shows 2 of the values (last time I ran it I believe it only showed the at11 and at12 column values).

This type of PHP looping through columns of one record for this scenario is new to me so any advice or pointing to a tutorial would be greatly appreciated.


If you do:




you will see all the contents of your single result set.

You ought to be able to display each column by name:

echo $gl[0][‘at01’];

From memory, if using mysql_fetch_assoc is used and only returns one result set it still sticks it in an associated array, hence the need for $gl[0].

To loop through that result set without knowing the column names you could do:

foreach( $gl[0] as $key=>$value)
echo $key , ' is ' , $value ;

Fetch_assoc will return a 1 dimensional associative array (in all cases), so the [0] is not needed.