簡體   English   中英

將兩個字段插入數據庫

[英]Inserting two fields into a database

我正在努力使用MVC架構將數據和category_id添加到數據庫中。

這是我的控制器方法,可能全都錯了。

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

這是我的模型方法:

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

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

    return $categories->result();
}

最后,這是我想要能夠為笑話選擇類別的形式:

<?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(); ?>

在我剛剛開玩笑標簽之前(盡管它確實在數據庫中添加了數據),由於某種原因,它僅添加了“ 0”。

我一直在看一些專注於插入數據的CRUD教程,這是我能想到的最好的!

您沒有在控制器中檢查是否提交了表單。

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

試試這個,我認為這會工作

//controller
public function create(){
    $data = array(
        'joke' => $this->input->post('joke'),
        'category_id' => $this->input->post('category')
    );

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

public function selectdata(){
    $data['categories'] = $this->get_m->get_joke_categoryid();
}


//model
function createJoke($data){
            $this->db->insert('joker', $data);
            $this->session->set_flashdata("message", "Contract record successfully created.");

function get_joke_categoryid(){
    $query = $this->db->get('joker');
    return $query->result();
}

請檢查此代碼是否可以幫助您

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM