Codeigniter集成日期选择器后无法将选中日期提交至数据库
Let's break down why your controller is showing the current date instead of the selected one, and fix it step by step.
First, Debug the Raw Input
Before jumping into fixes, let's confirm what's actually being sent to the controller. Replace your current deadline code with this to check the raw POST value:
$rawDeadline = $this->input->post('deadline'); var_dump($rawDeadline); // This will tell you if the value is coming through at all
If this outputs NULL or an empty string, the problem is with how the frontend is submitting the data. If it shows the selected date (like 2024-05-20), then the issue is in how you're processing it.
Common Issues & Fixes
1. Form Method Mismatch
Make sure your <form> tag uses method="post". If you're using method="get", the value will be in the GET parameters instead of POST, so you need to use:
$rawDeadline = $this->input->get('deadline');
2. Input Field Isn't Inside the Form
Double-check that your <input type="date" name="deadline"> is wrapped inside the <form> element. If it's outside, the browser won't include it when submitting the form.
3. Empty Value Handling
If the user doesn't select a date, $this->input->post('deadline') will be empty. The problem is that strtotime('') returns the current timestamp, which is why you're seeing the current date. Fix this by adding a check for empty values:
$deadlineInput = $this->input->post('deadline'); if (!empty($deadlineInput)) { $deadline = date("Y-m-d", strtotime($deadlineInput)); } else { // Option 1: Keep default current date (but now it's intentional) $deadline = date("Y-m-d"); // Option 2: Set to null or show an error to the user // $deadline = null; // $this->session->set_flashdata('error', 'Please select a deadline date.'); } var_dump($deadline);
4. Third-Party Datepicker Conflict
You added the datetimepicker class to your input—if you're using a jQuery UI or other datepicker plugin, make sure it's properly syncing the selected value to the native <input type="date"> field. Some plugins hide the native input and use their own, so you need to ensure the plugin updates the name="deadline" input's value.
5. Check Browser Dev Tools
Open your browser's Developer Tools (F12), go to the Network tab, submit the form, and look at the request's Form Data. This will show exactly what values are being sent to the controller. If deadline isn't listed here, the issue is definitely on the frontend.
Once you fix the root cause, your controller should correctly pick up the selected date!
内容的提问来源于stack exchange,提问作者Minh Tra

