如何在codeigniter中更新数据时显示所选选项get by id

yul*_*din 1 php mysql codeigniter

我想在select选项标签中显示一个选定的值,具有特定的id,我有一个post表

+---------+-------------+---------------+-------------+
| post_id | post_title  | post_content  | category_id |
+---------+-------------+---------------+-------------+
| 1       | Title One   | Content One   | 1           |
+---------+-------------+---------------+-------------+
| 2       | TitleTwo    | Content Two   | 1           |
+---------+-------------+---------------+-------------+
| 3       | Title Three | Content Three | 2           |
+---------+-------------+---------------+-------------+
Run Code Online (Sandbox Code Playgroud)

然后我有一个类别表

+-------------+----------------+
| category_id | category       |
+-------------+----------------+
| 1           | Category One   |
+-------------+----------------+
| 2           | Category Two   |
+-------------+----------------+
| 3           | Category Three |
+-------------+----------------+
Run Code Online (Sandbox Code Playgroud)

我用select选项标签显示类别

控制器添加

function add(){
    if ($this->input->post('submit'){
        $data = array(
            'post_title' => $this->input->post('post_title'),
            'post_content' => $this->input->post('post_content'),
            'category_id' => $this->input->post('category_id'));
        $this->db->insert('post_table',$data);
    }
    $data[cats] = $this->db->get(category_table)->result();
    $this->load->view('view_add_post');
}
Run Code Online (Sandbox Code Playgroud)

查看添加,

<form method="post" action="<?php echo base_url();?>index.php/post/add">
    <input type="text" name="post_title">
    <textarea name="post_content"></textare>
    <select name="category_id">
        <?php foreach ($cats as $category) { ?>
        <option value="<?php echo $category->category_id ?>"><?php echo $category->category?>
        <?php } ?>
    </select>
    <input type="submit" name="submit" value="Save">
</form>
Run Code Online (Sandbox Code Playgroud)

控制器编辑

function edit($id){
    $data['post'] = $this->db->get_where('post_table' array('post_id',$id))->row();
    $data['cats'] = $this->db->get('category_table)->result();
    $this->load->view('view_edit_post',$data)
}
Run Code Online (Sandbox Code Playgroud)

编辑视图

这是我想在下拉选择选项中显示类别的问题,其中所选择的是我输入的第一个,例如我已经输入了类别ID为1的帖子然后当我编辑选择选项中的类别1时自动选择,怎么做?

<select name="category_id">
    <?php foreach ($cats as $category) { ?>
    <option value="<?php echo $category->category_id ?>"><?php echo $category->category?>
    <?php } ?>
</select>

// the selected option is automatically
Run Code Online (Sandbox Code Playgroud)

对不起,我的英语不好.

K. *_*air 6

更改此代码

<select name="category_id">
<?php foreach ($cats as $category) { ?>
<option <?php if($category->category_id == "your desired id"){ echo 'selected="selected"'; } ?> value="<?php echo $category->category_id ?>"><?php echo $category->category?> </option>
<?php } ?>
</select>
Run Code Online (Sandbox Code Playgroud)

我实际上为你添加了一个提示,因为你的问题不是那么清楚.

您必须将所需的ID与所选类别相匹配