Depends on if you want to pull all the data at once, or if you want to pull it for just for a country.
Ideally you'd have 2 tables:
countries
cities- ID
- name
- countryID (foreign key, referencing ID from the countries table)
Yours is pretty close to the second table, minus the ID field, which isn't required, since you could use a primary key of (name, countryID) instead if you wanted to.
I'm assuming you already know how to connect to a MySQL database (mysql_connect and mysql_select_db for the basics, though keep in mind these "mysql_*" functions are essentially deprecated at this point; they're good for learning, but not so great for production sites):
To pull out all the cities from one country, given a country's ID:
PHP Code:
function getCities($countryID){
$cities = Array();
$result = mysql_query("SELECT name FROM cities WHERE countryID = '$countryID';");
while($row = mysql_fetch_assoc($result)){
$cities[] = $row['name'];
}
return $country;
}
To pull out all the countries in your database, you'd do:
PHP Code:
function getCountries(){
$countries = Array();
$result = mysql_query("SELECT ID, name FROM countries");
while($row = mysql_fetch_assoc($result)){
$counties[$row['ID']]['name'] = $row['name']; //This line pulls out the country name
$countries[$row['ID']['cities'] = getCities($row['ID']); //This line pulls out all the cities in that country
}
return $countries;
}
Then you'd just do:
PHP Code:
$countries = getCountries();
And you'll have your array filled with country IDs, names, and cities for each country. The array is a little different from yours, but you can modify it easily enough to return what you want.
It's not the most efficient way to do it, but it's a pretty generic way that demonstrates some basic mysql functions. If this is too complicated let me know, and I can simplify it a little to just fit your problem.
Bookmarks