doubu0897 2012-08-16 16:03
浏览 452
已采纳

使用MySql在数据库中输入日期值或空值

I have searched the site and although I have found questions and answers similar I haven't been able to find an answer. After 4 hours of searching I've decided to bite the bullet and ask the question.

I have 4 date fields in a form that aren't required. I would like it to enter a date into the database if one of the fields has an entry or null if any are left blank.

I have an if statement that checks if the value is empty and if so $value = null, otherwise use $value = date("Y-m-d",strtotime($_post['value'])) to convert it to a date and this works well.

The problem is in my query. If I use '$value' it will insert the date correctly but won't insert a null value because using 'null' makes sql think it's a string. If I use just $value the null inserts just fine but the date goes in as 0000-00-00.

Any advice would be very much appreciated

Thanks for the advice so far...

Null is allowed, this is my script...

if(empty($_POST['fp32_original_install_date'])){
$fp32_install = NULL;
    }else{
$fp32_install = date("Y-m-d",strtotime($_POST['fp32_original_install_date']));
 }

 $sql = "INSERT INTO accounts_cstm (id_c, support_c, install_date_c, sware_renewal_date_c, product_key_c, account_status_c, fp32_support_type_c, fp32_support_renewal_date_c, fp32_original_install_date_c) VALUES ('$Guid','$cdr_support', '$cdr_install', '$cdr_renew', '$prod_key', '$account_status', '$fp32_support', '$fp32_renew', $fp32_install)";

If I use in the query $fp32_install a null value goes in just fine but a date goes in as 0000-00-00, if I use '$fp32_install' the date goes in fine but a NULL value goes in as 1970-01-01 (probably because it sees 'NULL' as a string)

If I echo $fp32_install the value is shown as 2012-08-16 and the SQL type for the column is date and the default is NULL

  • 写回答

2条回答 默认 最新

  • doujin8476 2012-08-16 16:13
    关注

    If you are using posted values from a form, then $_POST['value'] will not be NULL.

    You should check for empty values instead.

    if($_POST['value']=="")
    {
        $value="NULL";
    }
    else 
    {
        $value="'".date("Y-m-d",strtotime($_POST['value']))."'";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器