<tr>
<td>Select location</td>
<td>
<select name="contractors" id="contractors" class="autofill" style="width:100%" onchange="fetch_con1(this.value);">
<option value="all" selected='selected'>All contractors</option>
<?php $location->location_options(); ?>
</select>
</td>
</tr>
以上是我的代码的一部分。当我选择位置时,如果我在页面刷新后单击提交按钮,则不会显示先前输入的位置。我通过调用function(<?php $location->location_options(); ?>)
来显示数据库中的位置。这个我的位置功能:
function location_options() {
global $db;
$query = 'SELECT * from locations ORDER by location_name ASC';
$result = $db->query($query) or die($db->error);
$options = '';
if ($location_id!= '') {
while($row = $result->fetch_array()) {
if ($location_id == $row['location_id']) {
$options .= '<option selected="selected" value="'.$row['location_id'].'">'.$row['location_name'].'</option>';
} else {
$options .= '<option value="'.$row['location_id'].'">'.$row['location_name'].'</option>';
}
}
} else {
while ($row = $result->fetch_array()) {
$options .= '<option value="'.$row['location_id'].'">'.$row['location_name'].'</option>';
}
}
echo $options;
}
这是我的位置功能
答案 0 :(得分:0)
如果在函数中定义了$location_id
,那么这可能会按预期工作,尽管如前一条评论中所指出的那样 - 您还应该从硬编码选项'All Contractors'中删除selected='selected'
function location_options() {
global $db;
global $location_id;
/* Assume that the javascript function sends a post / get request with location_id as a parameter */
if( isset( $_REQUEST['location_id'] ) ) $location_id=$_REQUEST['location_id'];
$query = 'SELECT * from locations ORDER by location_name ASC';
$result = $db->query($query) or die($db->error);
$options = '';
if( isset( $location_id ) && $location_id!= '' ) {
while( $row = $result->fetch_array() ) {
$selected=( $location_id == $row['location_id'] ) ? " selected='selected'" : "";
$options.='<option '.$selected.' value="'.$row['location_id'].'">'.$row['location_name'];
}
} else {
while( $row = $result->fetch_array() ) {
$options .= '<option value="'.$row['location_id'].'">'.$row['location_name'];
}
}
echo $options;
}