doumou1864 2014-01-29 14:34
浏览 55

将两个字段插入数据库

I am struggling to add data and a category_id in to my database using the MVC architecture.

here is my controller method, which is probably all wrong.

public function create(){
    $data['categories'] = $this->get_m->createJoke();


    $data = array(
        'joke' => $this->input->post('joke'),
        'category_id' => $this->input->post('category')
    );

    $this->get_m->createJoke($data);

    $this->load->view('create', $data);
}

Here is my model method:

function createJoke($data){
    // Retrieving categories from the database
    $categories = $this->db->query('SELECT * FROM category');

    $this->db->insert('jokes', $data);

    return $categories->result();
}

and finally, this is the form which i want to be able to select a category for a joke:

<?php  

echo form_open('home/create');
?>

<p>
    <label for="joke">Joke</label>
    <input type="text" name="joke" id="joke" />
</p>

<select class="category" name="category">
    <option value=0>Select something…</option>
    <?php foreach  ($categories as $category) { ?>
        <option value="<?php echo $category['category_id']; ?>"<?php echo $category_id == $category['category_id'] ? ' selected="selected"' : ''; ?>><?php echo $category['name']; ?></option>
    <?php } ?>
</select>

<p>
    <input type="button" value="Submit"/>
</p>

<?php echo form_close(); ?>

Before i just had the joke label up (although it did add data in the database), it only added a "0" for some reason.

I have been watching some CRUD tutorials which focus on inserting data, and this is the best i can come up with really!

  • 写回答

2条回答 默认 最新

  • drcx71276 2014-01-29 17:20
    关注

    You didn't check whether form is submitted or not in your controller.

    public function create(){
        $data['categories'] = $this->get_m->createJoke();
    
        if($this->input->post("joke")!="" and $this->input->post("category")!="") // check post have some value
        {
           $data = array(
              'joke' => $this->input->post('joke'),
              'category_id' => $this->input->post('category')
           );    
           $this->get_m->createJoke($data);
        }
    
        $this->load->view('create', $data);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题