目前為止,我們學會了怎麼查詢資料和新增資料。
接下來,我們來寫刪除資料的方法。
首先,回到controller/students.php
新增:
public function remove()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Remove a student';
$this->form_validation->set_rules('student_name', 'student_name', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('class/remove',$data);
$this->load->view('templates/footer');
}
else
{
$data['title'] = 'remove success!';
$this->student_model->remove_student();
$this->load->view('class/success',$data);
}
}
接著到view/class
底下新增remove.php
並加入以下內容:
<h2><?php echo $title ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('index.php/students/remove') ?>
<label for="student_name">Name</label>
<input type="input" name="student_name" /><br />
<input type="submit" name="submit" value="Remove a student" />
</form>
再至student_model.php
新增:
public function remove_student()
{
$name = $this->input->post('student_name');
$this->db->where('name', $name)->delete('class');
}
然後打開 http://localhost/ci/index.php/students/remove
並輸入欲刪除的學生的名字
應該就可以看到Success了
回到http://localhost/ci/index.php/students/index 查看已經沒有該筆資料了