空字段保存空值在数据库

问题描述:

我有一个需要用户填写一份表格。它有必填字段,其他字段不是必需的。例如,需要员工信息字段被填满和配偶,不需要孩子和孩子的生日。每当我试图将数据保存在数据库中,同时使配偶和子女清空数据库也节省了一个空值和孩子的生日字段其datepickers节省了默认日历值1970-01-01。 这是在数据库中保存我的PHP代码。空字段保存空值在数据库

if (!empty($_POST['child']) && !empty($_POST['ch_DateOfBirth'])) { 
 

 
     $selectEmp=$dbcon->query("Select Emp_ID from employee"); 
 
     $count=$selectEmp->num_rows; 
 

 
     if ($count>0) { 
 
       while($row=$selectEmp->fetch_array()){ 
 
        $emp_id="".$row['Emp_ID'].""; 
 
       } 
 

 
     $child_name=$_POST['child']; 
 
     $count=count($child_name); 
 

 
      for ($i=0; $i < $count ; $i++) { 
 
       $child_bday=date('Y-d-m', strtotime($_POST['ch_DateOfBirth'][$i])); 
 
       $sql6="INSERT into tbl_children (Emp_ID, Ch_Name, Ch_Bdate) values ('".$emp_id."', '".$child_name[$i]."', '".$child_bday."') "; 
 
       $dbcon->query($sql6); 
 
      } 
 
     } 
 

 
}

这就是数据库显示。

enter image description here

+2

它设置为null。 – nogad

+0

日期必须在$ child_bday = date('Y-m-d',strtotime($ _ POST ['ch_DateOfBirth'] [$ i])); – kannan

使用array_filter()值从公布数组中删除空值。

$child_names = array_filter($_POST['child']); 
foreach($child_names as $key => $child_name){ 

    $child_bday = (isset($_POST['ch_DateOfBirth'][$key]))?date('Y-d-m', strtotime($_POST['ch_DateOfBirth'][$key])):NULL; 

    $sql6="INSERT into tbl_children (Emp_ID, Ch_Name, Ch_Bdate) values ('".$emp_id."', '".$child_name."', '".$child_bday."') "; 
      $dbcon->query($sql6); 
} 
+0

谢谢!这工作。 – Laurie

允许空值在数据库即设置默认值null,例如,

`CREATE TABLE emptable(
`empname` VARCHAR(30) NOT NULL, 
`dob` date DEFAULT NULL);` 

默认日历值输入到数据库中,因为空值转换为1970-01-01当你执行date('Y-d-m', strtotime($_POST['ch_DateOfBirth']

所以,检查日期为空,然后将其转换为日期格式只有在它里面

for ($i=0; $i < $count ; $i++) { 
       $child_bday=""; 
       //converts to date format only if the date field is not empty..else its null 
       if(!empty($_POST['ch_DateOfBirth'][$i]) 
       { 
       $child_bday=date('Y-d-m', strtotime($_POST['ch_DateOfBirth'][$i])); 
       } 
       $sql6="INSERT into tbl_children (Emp_ID, Ch_Name, Ch_Bdate) values ('".$emp_id."', '".$child_name[$i]."', '".$child_bday."') "; 
       $dbcon->query($sql6); 
      } 

没错:你需要改变你的表列 “Ch_Bdate”

ALTER TABLE table_name CHANGE `Ch_Bdate` `Ch_Bdate` DATETIME NULL DEFAULT NULL;