I am learning Codeigniter 2 and successfully playing around with their Tutorial/Example about how to create a basic news application.
So after getting this working, I wanted to try to add a “delete record” link to the news item to see if I could figure this out on my own.
I added this to my models file, news_model.php:
public function delete_news($id) {
$this->db->delete('news', array('id' => $id));
}
I added this to my controllers file, news.php:
public function delete($id) {
$this->news_model->delete_news($id);
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News item deleted';
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}
I added this to my views file, index.php:
<a href="/news/delete/<?php echo $news_item['id'] ?>">Delete Item</a>
And finally, I added this to my config file, routes.php
$route['news/delete/(:any)'] = 'news/delete/$1';
It appears to be working as written.
From the News listing page at /news/, I click on the link for the news item and when the page reloads, the corresponding item is gone.
Questions:
1) After the page reloads, the URL is showing /news/delete/id, where /id is the item number. But, I don’t want this new URL, I really just want the /news/ page to reload to show the new content. Obviously, the way I did this is potentially dangerous, because a simple page refresh by the user would delete another item. What is the standard way to fix/handle this?
2) In my Controller delete() function, after the first line, I am basically just repeating the same 5 lines of code from the Controller index() function. No doubt this is somehow related to question #1, but again, what is the better way to do this?
3) Anything else I missed relating to “standard” or “best practice”?
Thank-you to Jean-François G. B. and Stephan S. for pointing me in the right direction.
This is the working solution…
controllers file,
news.php:EDIT:
Modified to display a confirmation message, “record #x deleted”…
and inside views file,
index.php: