基本上我想要做的就是从我的视图页面中显示特定的文章,然后有一个删除链接到一个页面,该页面带有一个字段和一个用于删除该字段中显示的 id 的文章的按钮。
在过去的几天里,我尝试将 id 放在 URL 链接中,即“delete?id=20”并尝试使用 $_GET 访问它,然后我尝试了“delete/20”和 URI段。然后我尝试使用会话等,但我不确定哪个是最好的,因为我没有让它们中的任何一个工作。
我决定展示我未修改的代码并从头开始这是我的代码:
视图.php
<?php
echo '<h2>'.$news_item['title'].'</h2>';
echo '<p>'.$news_item['text'].'</p>';
?><br><br>
<a href="http://website.com/CodeIgniter/index.php/news">
Go to latest news</a>
<a href = "http://website.com/CodeIgniter/index.php/news/delete">Delete</a><br>
删除.php
<h2>Delete a news item</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/delete') ?>
<form>
<label for="delete">Article Number</label><br>
<input name="id" class="resizedTitlebox" value="id" /><br>
<br>
<input type="submit" name="submit" value="Delete news item" /></form>
news.php(控制器)
<?php
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
}
public function view($slug)
{
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
public function delete() {
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Delete news item';
$this->form_validation->set_rules('id', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('news/delete');
$this->load->view('templates/footer');
}
else
{
$data['id'] = $this->news_model->delete('id');
$this->load->view('news/success');
}
}
}
news_model.php(模型)
<?php
class News_model extends CI_Model {
public function __construct() {
$this->load->database();
}
public function get_news($slug = FALSE){
$this->load->helper('text');
if ($slug === FALSE){
$this->db->order_by('id', 'desc');
$query = $this->db->get('news');
return $query->result_array();
}
$query = $this->db->get_where('news', array('slug' => $slug));
return $query->row_array();
}
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'id' => $this->input->post('id'),
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text'));
return $this->db->insert('news', $data);
}
public function delete ($id) {
$this->db->where('id',$this->input->post('id'));
$this->db->delete('news');
}
}
路由.php(配置)
$route['news/(:any)'] = 'news/view/$1';
$route['news/delete'] = 'news/delete';
$route['news'] = 'news';
$route['default_controller'] = 'news';
$route['404_override'] = '';
提前感谢您提供的任何帮助!
@jeroen 回答
“您没有在删除链接中传递任何值;您应该在路径或查询字符串中添加一个 ID” - 我假设您的意思是
<a href = "http://website.com/CodeIgniter/index.php/news/delete?article_id=<?php echo $news_item['id']; ?>">Delete</a>
所以使用article_id。那我可以在delete控制器中定义article_id吗?我不确定如何做到这一点。
答案:$this->input->get(article_id)