Jump to content

Accessing specific records from a query


Ewan

Recommended Posts

Hi all,

 

I've got a MySQL database which stores monthly records from a weather station.  I want to display info from this on a web page.  Some data is already displayed as graphs but I want to add some trivia based on the current month.

 

eg The wettest <current_month> was in <year1> when <Rain1>mm fell, followed by <year2> (<Rain2>mm) and <year3> (<rain3>mm).

 

The query to get the data is

$query= mysql_query ("SELECT Year, Rain FROM historical_data WHERE Month = '$current_month' ORDER By Rain DESC"); 
$data = mysql_fetch_array ($query);

 

I want to show the top 3 records, laid out as shown above, and not as a table, which would have been easier of course!

 

How do I access data from the returned array to do this?

 

MySQL version is 4.1.22.

 

Thanks.

Link to comment
Share on other sites

Here's the code I use:

 

$result = mysql_query( "..." );

while ( ($row=mysql_fetch_assoc( $result )) != false )
{
  echo $row['field'], '<br />';
}

 

mysql_fetch_assoc returns an 'associative' array so you can reference your fields with, in your case, $row['Year'] and $row['Rain']. Inside the while loop you'd put your code to output whatever HTML you need.

Link to comment
Share on other sites

Thanks for your quick replies, but I'm still unclear how this would work in practise.

 

Surely using a while loop will simply show one record followed by the next and I couldn't insert records from different rows into different places in a block of text as I want to?

 

eg The wettest October was in 1967 when 136mm fell, followed by 2004 (115mm) and 1979 (98mm).  (different colours here representing different returned records).  Is there a way to reference specific records in this way?

 

@fenway - Thanks.  I've used LIMIT, just forgot to mention it in the thread.  I've got year and month in different fields because that's how the data is supplied.  The fields in the db are: Year, Month, MaxTemp, MinTemp, Rain.

You can output it however you desire...

 

Outputting it all as I desire is what I'm struggling with ;)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.