Ben
Ben

Reputation: 687

Accessing a country list from a mySQL table or from a CSV table

For a web-register form I need to ask for the country. For this purpose I want to provide a given list with some 300 entries in a selectelement.

What is more fast and makes more sense , accessing a list from a mySQL DB table or from a CSV file ?

Upvotes: 3

Views: 178

Answers (1)

WebChemist
WebChemist

Reputation: 4411

You might try storing the country list as a cached json file, since this list will likely not be changing much. You can just write a script so that whenever your database table of countries is updated, it writes it out to the json file. And you can use local storage to prevent having to redownload the json cache file after the first page load:

jQuery:

$(document).ready(function(){

    // check to see if the list is already cached
    // if not download and store in local storage cache
    if(localStorage.getItem('list_country') === null)
    {
        $.get(
             '/cache/list_country.json'
            ,function(data){
                localStorage.setItem('list_country', JSON.stringify(data));
            }
        );
    }

    // use the stored cache to populate the select list
    $.each($.parseJSON(localStorage.getItem('list_country')), function(k, v){
        $('#country').append($('<option>').val(k).text(v));
    });
}

HTML:

<select id="country">
    <option value="" selected disabled>Please Select</option>
</select>

PHP (to update cache file)

// list is key/value pairs from SELECT id, name FROM database table like
$list = array("US"=>"United States","FR"=>"France"); //etc

$file_path = $_SERVER['DOCUMENT_ROOT'].'/cache/list_country.json';
$handle = fopen($file_path.$this->cache_file, 'w');
fwrite($handle, json_encode($list));
fclose($handle);

JSON:

{"US":"United States","FR":"France"} // etc

Upvotes: 1

Related Questions