/    Sign up×
Community /Pin to ProfileBookmark

populating country state city dropdown from database

Hi,

i was unsure about where to post this question since its php, mysql and ajax related. I want to build a dropdown with countries, states and cities. States box gets populated upon country selection and city box gets populated upon state selection as well. I already have a database with all the data but i really dont know whats the best way to load that data from my php page.

All the data is in on single table split into the following fields:
country_code, country_name, region_code, region_name, city, zipcode latitude, longitude and metrocode. Im not interested in zipcode and the last 3 so i stick with the date of the remaining fields. This is an example of the data in the fields:

DK Denmark 18 Midtjyllen Tranbjerg

I have several code examples but none of them seem to be suitable for using a database. Could you please help me?

Thank you.

to post a comment
PHP

19 Comments(s)

Copy linkTweet thisAlerts:
@DasherOct 14.2010 — This code is for selecting an article from a database but the concept is similar to what you need;
[code=php]
echo "<select name="selectedid" size='1'>";
echo "<OPTION value="0" label="New Article">New Article</OPTION>"
$query = "SELECT ID, Title FROM content WHERE ID >=1 ORDER BY ID DESC LIMIT ". $numArticles2Sel." ";
//echo $query."<br>";
$result = mysql_query ($query,$link);
//echo "SELECTED ? = ".$articleID."<BR>";
while ($a_row = mysql_fetch_array ($result, MYSQL_BOTH)){
if ($articleID == $a_row[0]){$isSel = " SELECTED ";}else {$isSel="";}
echo "<OPTION ".$isSel." value='".$a_row[ID]."' label='".$a_row[Title]."' >".$a_row[Title]."</OPTION>n";
}

echo "</SELECT>";[/code]


The city name is best done in AJAX once the state has been determined. But pulling the data from the database is similar.
Copy linkTweet thisAlerts:
@supercainauthorOct 14.2010 — Thanks. I got a snippet of code and tried to modify it in order to generate the dropdowns. I manage to get the state dropdown populated but not so the city dropdown which doesnt even appear

[CODE]<? $currentpage= basename($_SERVER['SCRIPT_FILENAME']);?>

<SCRIPT language=JavaScript>
function reload(form)
{
// Setting the variable with the value of selected country's ID
var val=populate.countryList.options[populate.countryList.options.selectedIndex].value;

// Sending the country id in the query string to retrieve the state list
self.location='<? print $currentpage;?>?countryId=' + val ;
}

function reload2(form)
{
// Setting the variable with the value of selected state's ID
var val2=populate.stateList.options[populate.stateList.options.selectedIndex].value;

// Sending the state id in the query string to retrieve the city list
self.location='<? print $currentpage."?".$_SERVER['QUERY_STRING'];?>?stateId=' + val2 ;
}
</script>
<? print $currentpage ;?>
<?php

/*
- Function to return the Country list as an array
- The array can be generated from a database resultset
*/
function getCountryList()
{
// Country List array
$countryList = array (
'1' => 'Bangladesh',
'2' => 'USA',
'3' => 'UK'
);

return $countryList;
}

/*
- Function to return the state list as an array
- Country ID is used to generate the state list
*/
function getStateList($countryId)
{
// State list array
// First key of the array is the Country ID, which holds an array of State list
$stateList = array (
'1' => array ('Dhaka'=> 'Dhaka','Chittagong', 'What else'),
'3' => array ('London'=> 'London', 'Cannot Remember'),
'2' => array ('Washington', 'N.Y.', 'etc')
);

return $stateList[$countryId];
}

function getCityList($stateId)
{
// City list array
// First key of the array is the State ID, which holds an array of City list
$cityList = array (
'Dhaka' => array ('Dhaka', 'Chittagong', 'What else'),
'London' => array ('London', 'Cannot Remember'),
'2' => array ('Washington', 'N.Y.', 'etc')
);

return $cityList[$stateId];
}
?>


<form action="populate.php" name="populate">

<?
// Retrieving the country list
$countryList = getCountryList();

// Setting the variable if the country is selected for its state list
@$countryId = $_GET['countryId'];

// Retrieving the state list if a country is selected
$stateList = ($countryId) ? getStateList($countryId) : null;

// Retrieving the state list
$stateList = getstateList($countryId);

// Setting the variable if the state is selected for its city list
@$stateId = $_GET['stateId'];

// Retrieving the city list if a state is selected
$cityList = ($stateId) ? getCityList($stateId) : null;



if (!empty($countryList))
{
// Generating the country drop down menu
echo "<select onChange='reload(this.form)' name='countryList'>";
foreach ($countryList as $key => $value)
{
echo "<option value='$key'";

if ($countryId == $key)
echo "selected";

echo ">$value</option>";
}
echo "</select>";
}

if (!empty($stateList))
{
// Generating the state drop down menu if a country is selected
echo "<select onChange='reload2(this.form)' name='stateList'>";
foreach ($stateList as $key => $value)
{
echo "<option value='$key'";

if ($stateId == $key)
echo "selected";

echo ">$value</option>";
}
echo "</select>";
}


if (!empty($cityList))
{
// Generating the city drop down menu if a state is selected
echo "<select name='cityList'>";
foreach ($cityList as $key => $value)
{
echo "<option value='$key'>$value</option>";
}
echo "</select>";
}

?>
</form>[/CODE]



i havent modified it yet to load the values from the database because i think its better to make it work the way its supposed first, and then i can make further mdoifications. Any idea why the code doesnt work?

Thank you.
Copy linkTweet thisAlerts:
@DasherOct 15.2010 — The code is mixing <? ?> php shortcut with <?php ?> php normal. The php shortcut is normally disabled in most servers by default and is not recommended for use since other script languages use the same notation.
Copy linkTweet thisAlerts:
@supercainauthorOct 16.2010 — I changed everything to <?php but still wont work. Any ideas please?
Copy linkTweet thisAlerts:
@007JulienOct 16.2010 — Just a old page and a his variant. Build with PHP, this pages needs only js files... (see comini.js in variant with change the js file).

Sorry for the french Régions, Départements and Communes...
Copy linkTweet thisAlerts:
@supercainauthorOct 18.2010 — Thats good but it contains only a few options so it needs no database, for cities and regions of all the countries of the world there is thousands of records so you need a database for sure.
Copy linkTweet thisAlerts:
@007JulienOct 18.2010 — Yes obviously (at home) too build and update your javascript files.

But this solution manage the serveur witch don't use DataBase nor PHP !

At least your files are easy too moove...
Copy linkTweet thisAlerts:
@supercainauthorOct 20.2010 — I understand what you mean, but that doesnt resolve my problem because all the date i have is on a database and i must fetch it from there so i need a code that does that.
Copy linkTweet thisAlerts:
@007JulienOct 20.2010 — There are several tasks :
[LIST=1]
  • [*]Manage drop down lists,

  • [*]Building data arrays or objects,

  • [*]Load these things on a page.

  • [/LIST]

    For drop down lists you can see this page http://javascript.internet.com/forms/country-state-city-drop-down-list.html .

    To build larger arrays (and lighter) than in this example
    [code=html]
    <script type="text/javascrip">
    var states = new Array();
    states['Canada'] = new Array('Alberta','British Columbia','Ontario');
    states['Mexico'] = new Array('Baja California','Chihuahua','Jalisco');
    states['United States'] = new Array('California','Florida','New York');

    // City lists
    var cities = new Array();
    cities['Canada'] = new Array();
    cities['Canada']['Alberta'] = new Array('Edmonton','Calgary');
    cities['Canada']['British Columbia'] = new Array('Victoria','Vancouver');
    cities['Canada']['Ontario'] = new Array('Toronto','Hamilton');

    cities['Mexico'] = new Array();
    cities['Mexico']['Baja California'] = new Array('Tijauna','Mexicali');
    cities['Mexico']['Chihuahua'] = new Array('Ciudad Juárez','Chihuahua');
    cities['Mexico']['Jalisco'] = new Array('Guadalajara','Chapala');

    cities['United States'] = new Array();
    cities['United States']['California'] = new Array('Los Angeles','San Francisco');
    cities['United States']['Florida'] = new Array('Miami','Orlando');
    cities['United States']['New York'] = new Array('Buffalo','new York');
    </script>[/code]

    You should use the codes (for select values) with, for exemple, arrays or objects like this (canada) :
    [code=html]
    // The cities are in alphabetic order
    var cities=['Calgary',1,'Edmonton',1,'Hamilton',3,'Toronto',3,'Victoria',2,'Vancouver',2];
    // 1 2 et 3 are the states (or regions) codes
    var states={'1':'Alberta','2':'British Columbia',3:'Ontario'};
    // To select the cities from British Columbia (code 2) :
    for (i=0;i<cities.length;i+=2) if (cities[i+1]==2) {...}
    [/code]

    Than you have to makes request with PHP and SQL (See the documentation) on your data base (mySQL ?) to select all cities and states codes from Canada (order by cities) for build the canada.js (or codeCanada.js) file like this :
    [code=php]$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
    if (!$link) {die('Could not connect: ' . mysql_error());}
    echo 'Connected successfully';
    $query = "SELECT * FROM content WHERE ID... ORDER BY cities";
    //echo $query."<br>"; to see what you do
    $result = mysql_query ($query,$link);
    $chnCts='';
    while ($a_row = mysql_fetch_array ($result, MYSQL_BOTH)){
    // foreach ($a_row as $k=>$v) echo "$k=>$v<br>"; to see what you get
    $chnCts.=',"'.$a_row["cities"].'",'.$a_row["codeStates"];
    }
    // the first comma is to delete
    $chnCts='var cities=['.substr($chnCts,1).'];';
    $fci=fopen("canada.js","w+");
    fwrite($fci,$chnCts);
    fclose($fci);[/code]


    Last, but not least you have to charge this files. You can first reload pages (with querystring in the uri to pass the country) to change the script (build a page type with XXX for the javascript file, read it with PHP and replace XXX with the CountryCodes after à request). After you can see [I]Comini.js[/I] to change the script dynamically or use AJAX with JSON ... etc.

    Good luck
    Copy linkTweet thisAlerts:
    @007JulienOct 20.2010 — With AJAX it will be possible to use light strings (without JSON) like this :
    [code=html]var cities="Calgary|1|Edmonton|1|Hamilton|3|Toronto|3|Victoria|2|Vancouver|2";
    // Than a simple split give the tab
    var tabCts=cities.split(/|/g);[/code]
    Copy linkTweet thisAlerts:
    @supercainauthorOct 20.2010 — Thats very useful information. Thank you so much for your kindness. I will give it a try and let you know about the results.

    Thank you!
    Copy linkTweet thisAlerts:
    @supercainauthorOct 25.2010 — Hi again,

    i finally got some time to try out your suggestions. I have some questions.

    The php code you provided creates a .js file. Does it mean i have to put a code like that for each country so it creates a.js file for each country as well? cant the page load the cities and states directly from the database without having to create a .js file first?

    thank you.
    Copy linkTweet thisAlerts:
    @007JulienOct 25.2010 — You can obviously build the cities and states pages with each pages. In my opinion it's a lot of work for the server... Keep this way for updating your files. See, for exemple, this page wich don't use php !

    It's now possible to dynamically replace an external JavaScript or CSS file in your page. Than a .js files for each page (in a loop with requests for countries in PHP) is probably the best solution.
    Copy linkTweet thisAlerts:
    @supercainauthorOct 25.2010 — I found a very good sample of exactly what i need. http://www.singlescrowd.com/

    i wonder how it works. I can copy the javascript code from there and use it at my site. However, im not sure where is that site loading the cities from. I like it also because it automatically detects your location which is very cool. Hope you can give me a hint. I rally appreciate your help.
    Copy linkTweet thisAlerts:
    @007JulienOct 25.2010 — I have tried to detect location (with PHP and IP adresses), but i live in normally Versailles (i am mow in Dordogne with bad connection) and was in Montpellier ??? Sorry for this short response...
    Copy linkTweet thisAlerts:
    @supercainauthorOct 26.2010 — Ahh, maybe its not as exact as for detecting your current location but anyway, the really important thing is the dropdown itself. I think i have identified the code that does that, but i have no idea on how it loads the info from the database.

    [CODE] function onCountryChange() {
    var component = $(COUNTRIES_LIST_ID);
    var callback;
    var countryId;
    var regionsList = $(REGIONS_LIST_ID);
    var isUsa;

    if (component.selectedIndex < 0) {
    countryId = 0;
    } else {
    countryId = component.options[component.selectedIndex].value;
    }

    doUsaSelectionLogic();
    isUsa = isUsaSelected();

    if (!isUsa) {
    onUsaNotSelected();
    regionsList = fastClearOptions(REGIONS_LIST_ID);
    regionsList.disabled = true;
    callback = function (count) {
    if (count > 1) {
    insertFirstOption(regionsList, "Choose region", 0, false, true);
    regionsList.selectedIndex = 0;
    }
    regionsList.disabled = false;
    onRegionChange(regionsList);
    };
    getRegionsListByCountryId(countryId, regionsList, callback);
    }

    }


    // Do all logic on region change.
    function onRegionChange() {
    var component = $(REGIONS_LIST_ID);
    var callback;
    var regionId;
    var citiesList = $(CITIES_LIST_ID);

    if (component.selectedIndex < 0) {
    regionId = 0;
    } else {
    regionId = component.options[component.selectedIndex].value;
    }

    citiesList = fastClearOptions(CITIES_LIST_ID);
    citiesList.disabled = true;

    callback = function (count) {
    if (count > 1) {
    insertFirstOption(citiesList, "Choose city", 0, false, true);
    citiesList.selectedIndex = 0;
    }
    citiesList.disabled = false;
    };
    getCitiesListByRegionIdWithGeoInfo(regionId, citiesList, callback);

    } [/CODE]


    and thats about it. But the code that dynamically changes the region and cities must be php or something because i cant find it on th source.

    Thank you.
    Copy linkTweet thisAlerts:
    @007JulienOct 28.2010 — See tools.js. They use Ajax request and a SOAP Service with thre functions :
    [code=html]function getCitiesListByRegionIdWithGeoInfo(idRegion, listBox, callback){}
    function getCitiesListByCountryId(idCountry, listBox, callback){}
    function getRegionsListByCountryId(idCountry, listBox, callback){}[/code]
    All this functions call this service
    [code=html]askSoapService('/ws/GeoService', 'GeoService', xml, internalCallback);[/code]
    Copy linkTweet thisAlerts:
    @supercainauthorOct 29.2010 — But they must be using php code as well, arent they? im pasting the whole source onto my web page and linking all their files directly but it wont work.
    Copy linkTweet thisAlerts:
    @007JulienNov 03.2010 — Yes, they work probabily with PHP (or ASP ?). The url '/ws/GeoService' is only a workspace on the same server, where they can read informations from an other server with a subscription to this SOAP service.
    ×

    Success!

    Help @supercain spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.16,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...