Forum Moderators: coopster

Message Too Old, No Replies

Is there any other way to do this query.

php / mysql

         

le_gber

7:14 pm on May 28, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have a news section on my site that displays a list of ... news. The news are sorted monthly and you rougthly get 5 news per month. The list displays the news headline and the month it belongs to (one). Both are coming from the database.

I have created a php function to display this and it looks like the following (pseudo code):



function myfunct(){
query1 = query the database to get DISTINCT months
while there are some month in query1 array_push the month in $newsMonthArray
array_flip($newsMonthArray)

foreach($newsMonthArray as $month){
query2 = query the database to get all the news
while there are some news
if the news belong to that month print it
}//end while
}//end foreach

}//end function

the output looks like this
Month 1:

  • news 1 month 1
  • news 2 month 1
  • news 3 month 1
    Month 2:
  • news 1 month 2
  • news 2 month 2
  • news 3 month 2
    ...


    It is working fine at the moment, and the bit I would like to change is the red query looking for the news. Is there any way to have it outside of the foreach loop to only have one query to db instead of 1/month?

    I tried having it outside (with its corresponding while) but then I don't get any data past month 1.

    Hope this will make sense to someone :)

  • Habtom

    12:02 pm on May 29, 2007 (gmt 0)

    WebmasterWorld Senior Member 10+ Year Member



    This might be a solution. Take the query out of the foreach loop, write the query as follows:
    query2 = query the database to get all the news GROUP BY month.

    In the while loop write a code to treat the news separately to display them in the format you provided.

    Habtom