Page 1 of 1

looping lists

Posted: Fri Feb 06, 2004 5:11 am
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;
------------------------------------------------------------------------------------- :?:

Posted: Fri Feb 06, 2004 5:24 am
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

Posted: Fri Feb 06, 2004 5:25 am
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

Posted: Fri Feb 06, 2004 5:44 am
by memepool
top notch. thanks guys.