CodeIgniter 3博客应用:更新文章后重定向失败求助
Hey there! Let's get that post-update redirect sorted out for your CodeIgniter blog. This is a common hiccup, but easy to fix once you check a few key spots:
1. Verify Your Controller's Update Logic
First, make sure your update() method in the Posts controller is handling the redirect correctly after the post is successfully updated. Here's a clean example of how it should look:
public function update() { // Run form validation first (you should have this already!) $this->form_validation->set_rules('title', 'Title', 'required'); // Add other validation rules for content, author, etc. if ($this->form_validation->run() === FALSE) { // If validation fails, reload the edit view with existing data $data['post'] = $this->post_model->get_post($this->input->post('id')); $this->load->view('posts/edit', $data); } else { // Grab the post ID from the form submission $post_id = $this->input->post('id'); // Prepare update data $update_data = [ 'title' => $this->input->post('title'), 'content' => $this->input->post('content'), 'updated_at' => date('Y-m-d H:i:s') // Add timestamp if needed ]; // Update the post via your model $this->post_model->update_post($post_id, $update_data); // Redirect to the updated post's view page // Adjust the URL to match your route structure! redirect('posts/view/' . $post_id); } }
- Critical Check: Never output anything (like
echo,var_dump, or loading a view) before callingredirect(). CodeIgniter uses HTTP headers to redirect, and any prior output will break this functionality entirely.
2. Confirm the Post ID is Being Passed Correctly
Double-check that the hidden id field in your form is actually sending a valid value. Add a quick debug line at the top of your update() method to verify:
// At the start of update() $post_id = $this->input->post('id'); var_dump($post_id); // Should show a valid number, not NULL
If it's empty, ensure the $post->id variable is properly populated when you load the edit view (double-check your model's get_post method if needed).
3. Match Your Redirect to Custom Routes
If you've set up custom routes in application/config/routes.php, make sure your redirect URL aligns with those rules. For example, if you have:
// Custom route for single post view $route['post/(:num)'] = 'posts/view/$1';
Your redirect should use this custom URL instead:
redirect('post/' . $post_id);
4. Rule Out Output Buffering Conflicts
In rare cases, unintended output buffering can mess with redirects. If you're still stuck, try adding ob_clean() right before the redirect (though this is a band-aid—better to track down and fix any accidental output in your code):
ob_clean(); redirect('posts/view/' . $post_id);
Once you adjust these areas, your post update should smoothly redirect to the updated article's page.
内容的提问来源于stack exchange,提问作者Razvan Zamfir

