1
這是一個代碼優化問題比通常的直接問題更需要解決的問題。 我有4個選擇菜單,它們從SQL查詢中獲取它們的值。問題是我重複同樣的查詢4次來填充4選擇菜單列表。 下面是SQL代碼。(我使用PHP與SQL Server 2008)使用一個查詢來填充多選擇菜單HTML 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」部分放在頁面頂部,然後在選擇菜單html部分中使用「while」部分,但它僅適用於第一個菜單。其餘的都顯得空白。
我能比這更好嗎?還是這樣好?所有的幫助表示讚賞
如果您沒有任何影響結果的foreach語句,則此方法有效。仔細檢查我的代碼...對於每個項目,我選擇必要的細節。這隻適用於如果我只有一個項目在第一個foreach(國家作爲makassi1) – MaxI