如果已在数据库中选择,则消除Selected选项...?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如果已在数据库中选择,则消除Selected选项...?相关的知识,希望对你有一定的参考价值。
我有一个选项框,选项最多为20,例如,如果选择了选项5或任何其他选项并将其保存在特定列的数据库中,则下次不会显示... 请指导我
<select class="form-control text-center" name="code" id="Code" >
<option value="">Select Code</option>
<?php for($i = 1; $i <= 20; $i++){ ?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php } ?>
</select>
答案
控制器:
function index(){
//below code should be in Model this is only for example
$this->db->select('code');
$query = $this->db->get_where('hr_levels', array('created_by' => $_SESSION['username']));
if ($query->num_rows() > 0) {
$code = $query->row('code');
} else {
$code = 0;
}
$option = array();
for($i=1;$i<=20;$i++){
if ($code != $i) {//no need to add if in view, just pass the data to view
$option[$i] = $i;
}
}
$data['options'] = $option;
$this->load->view('option_view',$data);
}
视图:
<select class="form-control text-center" name="code" id="Code" >
<option value="">Select Code</option>
<?php foreach($options as $key => $value){
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php } ?>
</select>
另一答案
你可以像这样接近它
$availableOption = range(1,20);
$selectedOrInDb = [5,6,8,9]; // Selected OR from DB
$remaining = array_diff($availableOption, $selectedOrInDb);
现在你可以使用$remaining
循环
<select class="form-control text-center" name="code" id="Code" >
<option value="">Select Code</option>
<?php foreach($remaining as $key => $value){ ?>
<option value="<?php echo $value; ?>"><?php echo $value; ?></option>
<?php } ?>
</select>
另一答案
调节器
public function get_selected(){
$this->load->model('model_name');
$data['selected'] = $this->model_name->function_name($_SESSION['username']);
//Already saved values will be get on the basis of any condition
return $this->load->view('file.php');
}
模型
public function function_name($username){
return $this->db->get_where('table', ['created_by' => $username])->row()->value;
}
现在你已经在$selected
中获得了选定的值
<select class="form-control text-center" name="code" id="Code" >
<option value="">Select Code</option>
<?php for($i = 1; $i <= 20; $i++){
if($i != $selected)?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php } } ?>
</select>
以上是关于如果已在数据库中选择,则消除Selected选项...?的主要内容,如果未能解决你的问题,请参考以下文章