Jump to content

[SOLVED] Need help with Array and Foreach


brooksh

Recommended Posts

I know this should be something simple, but I can't figure it out. Can someone please help me? I have a table name cities with a field named cities that has "Austin,Los Angeles,New York,San Francisco,Seattle"  I want to grab each city from the field and display it. Here is what I have, but it is obviously wrong.

 

                $query = "SELECT * FROM cities WHERE country='US'";
                $result = mysql_query($query);
                $rows = mysql_num_rows($result);
                $i = 0;
                while ($i < $rows){
		$cities = $rows[cities];
		$cities = explode(",", $cities);
                    $name = mysql_result($result, $i, "city");
                    echo "$name<br>";
                    $i++;
                }

Link to comment
https://forums.phpfreaks.com/topic/86999-solved-need-help-with-array-and-foreach/
Share on other sites

If u want to simple show the cities,then use his simple code:

 

 
               $query = "SELECT * FROM cities WHERE country='US'";
                $result = mysql_query($query);
                $num = mysql_num_rows($result);
                while ($rows=mysql_fetch_object($result)){
		$cities = $rows->cities;
		$cities = explode(",", $cities);
                        echo $cities."<br>";
                   
                }

Is the column name cities? If so, try:

                $query = "SELECT cities FROM cities WHERE country='US'";
                $result = mysql_query($query) or die(mysql_error());
                while ($row = mysql_fetch_assoc($result)){
		$cities = $row['cities'];
		$cities = explode(",", $cities);
                        echo "$name <br>";
                }

If there is only a single record with country='US'

 

<?php
                $query = "SELECT cities FROM cities WHERE country='US'";
                $result = mysql_query($query);
                $cities = explode (',' , $mysql_result ($result, 0));
                foreach ($cities as $city)
                {
                      echo "$city<br/>";
                }

Thank you it works.

 

$result = mysql_query($query);
                $cities = explode (',' , mysql_result($result, 0));
                foreach ($cities as $city)
                {
                      echo "$city<br/>";
                }

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.