将两个字段插入数据库

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!

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

try this i think this will work

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

kindly check this if this code help you