这是一个代码优化问题,而不是通常的直接问题,需要解决的问题。 我有4个选择菜单,从SQL查询中获取它们的值。问题是我重复相同的查询4次以填充4选择菜单列表。 这是SQL代码。(我在SQL Server 2008中使用PHP)
<select name="cities" id="" class="brkcity" style="width:120px;">
<option></option>
<?php
foreach($country as $makassi1){ $selectcities = "SELECT City, Country, Rate FROM tblPerdiem_Rates WHERE Country = '$makassi1'";$checkcity = sqlsrv_query($conn,$selectcities, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ))or die(print_r( sqlsrv_errors(), true));
while($row=sqlsrv_fetch_array($checkcity))
{
$countries = ($row['Country']);
$names =($row['City']) ;
$rate =($row['Rate']) ;
$ratess=$names."-".$countries
?>
<option id="cityoptrates" value="<?php echo $rate; ?>"><?php echo $ratess; ?></option>
<?php
}
}
sqlsrv_free_stmt($checkcity);
?>
</select></td>
<td width="93" id="tdbreakfast"><input name="brkfastchk" class="breko" type="checkbox" value="" id="" />
<label for="brkfasttxt"></label>
<input style="" value="" name="brkfasttxt" class="breko" type="text" id="" size="3" readonly="readonly" />
<label for="brkfastchk"></label></td>
<td width="133" id="tdlnchcities"><select name="cities" id="" class="lnhcity" style="width:120px;">
<option></option>
<?php foreach($country as $makassi1) { $selectcities = "SELECT City, Country, Rate FROM tblPerdiem_Rates WHERE Country = '$makassi1'"; $checkcity = sqlsrv_query($conn,$selectcities, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ))or die(print_r( sqlsrv_errors(), true));
while($row=sqlsrv_fetch_array($checkcity))
{
$countries = ($row['Country']);
$names =($row['City']) ;
$rate =($row['Rate']) ;
$ratess=$names."-".$countries
?>
<option id="cityoptrates" value="<?php echo $rate; ?>"><?php echo $ratess; ?></option>
<?php
}
}sqlsrv_free_stmt($checkcity);
?>
</select>
这是我用来填充列表菜单的代码。但我不喜欢它,因为在同一页面中重复相同的查询4次是低效的。我尝试将查询和“for each”部分放在页面顶部,然后使用select菜单html部分中的“while”部分,但它只适用于第一个菜单。其余的都是空白的。
我可以做得比这更好还是这样做得好?所有帮助表示赞赏
答案 0 :(得分:3)
在数组中缓存单个查询的结果,然后使用该数组填充下拉列表:
$data = array()
while($row = sqlserv_fetch_array($checkcity)) {
$data[] = $row;
}
然后执行foreach循环而不是while / fetch:
foreach($data as $row) {
$countries = $row['Country'];
$city = $row['City'];
$rate = $row['rate'];
etc...
}
更新
你也可以缓存“per $ makassi1”,如果需要的话:
while(...) {
$data[$makassi1][] = $row;
}
但是,考虑重写您的查询以使用连接或其他结构,因此您不会运行那么多几乎几乎相同的查询。