looping lists

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
memepool
Forum Newbie
Posts: 4
Joined: Thu Feb 05, 2004 5:42 am
Location: London

looping lists

Post by memepool »

Trying to get it to cycle through the list and assign the results to a variable but it only picks up the last one. Any ideas?
-------------------------------------------------------------------------------------
$result = mysql_query ("SELECT* FROM postcodes");

while (list(,$areacode)= mysql_fetch_array($result)){

$areaone = sprintf (" %s", $result);

}


print $areaone;
------------------------------------------------------------------------------------- :?:
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

why not try this

Code: Select all

$result = mysql_query ("SELECT* FROM postcodes"); 

while ($line = mysql_fetch_array($result)){ 

    print $line['areaone'];

}

You might need to change the 'areaone' in print $line['areaone']; to whatever that column is called in your Database.

Mark
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Each time the loop runs the $areaone value is overwritten so you will only ever get the last value. Assigning the values to an array will store all of them:

Code: Select all

// name the fields you want to return from the table, you don't
// need to select all of them if you only want one
$sql = "SELECT areacode FROM postcodes";
$result = mysql_query($sql);

// create an empty areacodes array
$areacodes = array();

// loop through the results
while ($row = mysql_fetch_assoc($result)) {
    // assign the areacode value to the $areacodes array - you don't 
    // need to use sprintf() in fact you should unless you are formatting
    // a value
    $areacodes[] = $row['areacode'];
}

// view the results in the array:
echo '<pre>';
print_r($areacodes);
echo '</pre>';
Mac
memepool
Forum Newbie
Posts: 4
Joined: Thu Feb 05, 2004 5:42 am
Location: London

Post by memepool »

top notch. thanks guys.
Post Reply