如何使用Codeigniter将值从JQuery datepicker插入MySQL date数据类型?

我无法使用Date数据类型将我的JQuery Datepicker中的值插入到我的MySQL数据库中。 我将如何将字符串转换为日期数据类型? 即时通讯使用Codeigniter和MVC。 这是我的代码:

JavaScript的

 $(function() { $( "#datepicker" ).datepicker({ showOn: "button", buttonImage: "images/icons/calendar_24.png", buttonImageOnly: true, onSelect: function(dateText, inst){ $("input[name='dob']").val(dateText); } }); });  

调节器

 function create() { $data = array( 'FirstName' => $this->input->post('fname'), 'DateofBirth' => $this->input->post('dob') ); $this->site_model->add_record($data); $this->index(); } 

视图

  

多谢你们! 我在谷歌阅读了一些解决方案,我这样做了:

控制器:

 function create() { $date = $this->input->post('dob'); $data = array( 'FirstName' => $this->input->post('fname'), 'DateofBirth' => date('Ym-d', strtotime($date)) ); $this->site_model->add_record($data); $this->index(); } 

这解决了我的问题! 🙂

我假设您的MySQL表的dob列是DATE类型。 Date类型采用yyyy-mm-dd格式的值,例如2012-09-21

因此,要回答您的问题 – 您需要将日期从datepicker格式化为上述有效格式。 例如,如果您的日期选择日期是dd-mm-yy格式,则需要使用控制器中的php的date()函数将其转换为mysql日期格式….(还有其他方法可以处理datetime类等日期)

 function create() { $data = array( 'FirstName' => $this->input->post('fname'), 'DateofBirth' => date('Ym-d', strtotime(str_replace('-', '/', $this->input->post('dob')))); ); $this->site_model->add_record($data); $this->index(); } 

使用strtotime时注意()

m / d / y或dmy格式的日期通过查看各个组件之间的分隔符来消除歧义:如果分隔符是斜杠(/),则假设为美国m / d / y; 而如果分隔符是破折号( – )或点(。),则假定为欧洲dmy格式。

  

你的代码很好

 $(document).ready(function() { var year=new Date().getFullYear(); var yearTo=year-18; var yearFrom=year-100; //display the years from hundred years in the past till 18 years in the past $( "#datePickerDOB" ).live("click",function(){ $( "#datePickerDOB" ).datepicker({ changeMonth: true, changeYear: true, yearRange: yearFrom+":"+yearTo, dateFormat: "dd-mm-yy" }); }); }); 

使用以下格式设置datepicker的格式:

$(’#datepicker’)。datepicker({dateFormat:’yy-mm-dd’});

您的控制器应如下所示:

 { $date = $this->input->post('dob'); $data = array( 'FirstName' => $this->input->post('fname'), 'DateofBirth' => date('Ym-d', strtotime($date)) ); $this->site_model->add_record($data); $this->index(); } 

我认为这更适合你