Reputation: 687
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 select
element.
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
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