gpt4 book ai didi

php - 如何使用sql在php的选择框中显示先前选择的选择选项

转载 作者:行者123 更新时间:2023-11-30 22:37:45 25 4
gpt4 key购买 nike

<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;
}

这是我的定位功能

最佳答案

如果 $location_id 是在函数之外定义的,那么这可能会按预期工作,尽管正如在之前的评论中指出的那样 - 您还应该删除 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;
}

关于php - 如何使用sql在php的选择框中显示先前选择的选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31985936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com