题
我有这个php代码,用于做出下拉列表选择国家 /地区的选择,但我想消除此额外的mysql查询,只是将输出像在代码中一样存储在页面上如果我不使用查询获取数据,请选择建议
<select name="country" style="width:180px;" onChange="do_get_rest_popup(this.value)" o>
<?PHP
$sql="SELECT * FROM users_countries ORDER BY country";
$result_country = executequery($sql);
while($line_country = mysql_fetch_array($result_country)){
$db_country_id = $line_country['id'];
$country_name = $line_country['country'];
?>
<option value="<?=$db_country_id?>"<? if($line_member['country']==$db_country_id){ echo " SELECTED";} ?>><?=$country_name?></option>
<?
}
?>
</select>
关于在页面上输出此内容的代码,我已经为这篇文章减少了国家/地区的数量
<select name="country" style="width:180px;" onChange="do_get_rest_popup(this.value)" o>
<option value="217">Turkmenistan</option>
<option value="218">Turks and Caicos Islands</option>
<option value="219">Tuvalu</option>
<option value="220">Uganda</option>
<option value="221">Ukraine</option>
<option value="222">United Arab Emirates</option>
<option value="223">United Kingdom (Great Britain)</option>
<option value="224" SELECTED>United States</option>
</select>
解决方案
怎么样这样呢?
<?
$countries = array(
"217" => "Turkenistan",
"218" => "Turks and Caicos Islands",
"219" => "Tuvalu",
"220" => "Uganda",
"221" => "Ukraine",
"222" => "United Arab Emirates",
"223" => "United Kingdom (Great Britain)"
"224" => "United States");
?>
<select name="country" style="width:180px;" onChange="do_get_rest_popup(this.value)" />
<?php
$countryCounter = 1;
$amtOfCountries = count($countries);
foreach ($country as $id => $c) {
if ($countryCounter == $amtOfCountries) {
echo "<option value=\"$id\" SELECTED>$c</option>";
}
else {
echo "<option value=\"$id\">$c</option>";
$countryCounter++;
}
}
?>
</select>
编辑:我没有测试这一点,但你应该明白我的意思
其他提示
你可以:
- 使用 var_export() 将国家/地区数组打印为 PHP 代码,然后将其硬编码在某处。
- 使用类似的方法缓存数据库中的值 梨缓存_Lite - 这使用起来非常简单,这意味着如果您修改数据库中的值,您所要做的就是删除缓存文件以重新生成它。
通过上述两个选项,您将获得一个数组,您可以按照与现在正在执行的操作类似的方式循环遍历该数组,以生成 html。
您可以缓冲该静态HTML和做一个简单的字符串替换为选择的值。
1)保存国HTML列表分成countries.html
2)在加载时,读countries.html
到一个变量,并做了字符串替换:
$countries = file_get_contents('countries.html');
echo str_replace('value="'.$userCountry.'"','value="'.$userCountry.'" SELECTED',$countries);
不太存储器有效的整体,但它确实保存数据库击中和处理时间。
不隶属于 StackOverflow