franglais
franglais

Reputation: 938

PHP combining MySQL results to one variable

I'm trying to build a list of towns to add at the bottom of a site I'm working on and I can echo the variable fine within this block of PHP, however when I try to echo $result1 in another block of PHP it's only returning the first result, rather than the whole list.

Any ideas what's going on?

$result = mysql_query("SELECT town FROM jb_town_postcodes");
$results = array();
while($row = mysql_fetch_assoc($result))
echo $results1 =  $row['town'];

Upvotes: 0

Views: 500

Answers (4)

iiro
iiro

Reputation: 3119

while($row = mysql_fetch_assoc($result))
$results[]= $row['town'];

print_r($results);

Now

for example

echo $results[0] will print the first value e.g. Wolverhampton echo $results[2] will print Cannock

echo $results[count($results)-1] will print the last value

Upvotes: 3

David
David

Reputation: 4117

You should use curly brackets ;)

while($row = mysql_fetch_assoc($result))
{
  $results[]= $row['town']; 
}

Upvotes: 0

Vishal
Vishal

Reputation: 2181

Try this:

$result = mysql_query("SELECT town FROM jb_town_postcodes");
$results = array();

while($row = mysql_fetch_assoc($result))
  // at every iteration, store value of 
  // $row['town'] to new index of $results1
  $results1[] =  $row['town'];

// now use $results anywhere

Upvotes: 0

koral
koral

Reputation: 2955

Each iteration you save in you $result1 a new value from $result - that's why after loop you have only last town.

Upvotes: 0

Related Questions