0

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'];
2
  • incorrect var inside while loop, because it overrides each time until the loop ends Commented May 23, 2012 at 8:02
  • 1
    you just created an empty array but never used it Commented May 23, 2012 at 8:03

4 Answers 4

3
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

Sign up to request clarification or add additional context in comments.

3 Comments

You've answered it so quickly that Stack Overflow won't actually let me accept your answer yet :D Thanks!
how do I get it to show it not as an array, but a list of values? so rather than "Array ( [0] => Wolverhampton [1] => Tipton [2] => Cannock [3]" have "Wolverhampton Tipton Cannock"
for example echo $results[0] will print Wolverhampton and echo $results[2] will print Cannock
0

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

Comments

0

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

Comments

0

You should use curly brackets ;)

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

2 Comments

If you only put 1 command inside then you should not use them to make it more readable!
@peipst9lker maybe but if you have very much lines it's better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.