我正在努力使用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教程,这是我能想到的最好的教程!
答案 0 :(得分:0)
您没有检查控制器中是否提交了表单。
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);
}
答案 1 :(得分:0)
尝试这个我认为这将有效
//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();
}
如果此代码可以帮助您
,请检查此信息