This is the original coding. I have tried so many method from previous posting in stackoverflow but none of them works. My column for father, mother , husband and wife are in the integer type.
$db = mysqli_connect('x', 'xx', 'xxx', 'xxxx');
if (isset($_POST['add_member'])) {
  // receive all input values from the form
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $sex = mysqli_real_escape_string($db, $_POST['sex']);
  $father = mysqli_real_escape_string($db, $_POST['father']) == "" ? null : (int)mysqli_real_escape_string($db, $_POST['father']);
  $mother = mysqli_real_escape_string($db, $_POST['mother']) == "" ? null : (int)mysqli_real_escape_string($db, $_POST['mother']);
  $husband = mysqli_real_escape_string($db, $_POST['husband']) == "" ? null : (int)mysqli_real_escape_string($db, $_POST['husband']);
  $wife = mysqli_real_escape_string($db, $_POST['wife']) == "" ? NULL : (int)mysqli_real_escape_string($db, $_POST['wife']);
  $family = mysqli_real_escape_string($db, $_POST['family']) == "" ? null : (int)mysqli_real_escape_string($db, $_POST['family']);
    
    $query = "INSERT INTO users (username, gender, father_id, mother_id, husband_id, wife_id, family_id) VALUES ('$username', '$sex', '$father', '$mother', '$husband', '$wife', '$family')";
    mysqli_query($db, $query);
    header('location: index.php');
  }
}
Here are some methods I used but still not work
 $husband =  mysqli_real_escape_string($db, $_POST['husband']);
 $husband = !empty($husband_contact) ? "'$husband'" : NULL;
Another method:
if (empty($_POST['husband'])){ $husband= NULL; 
}else{ $husband =  mysqli_real_escape_string($db, $_POST['husband']);}
Another method (I am not sure about this because it donot have $db, is it even possible?):
 if ($_POST['husband'] == '') {
 $husband = NULL;
 }else {
  $husband = "'" . mysqli_real_escape_string($_POST['husband']) . "'";
 }
and another method (same with this, no $db)
$husband = !empty($_POST['husband']) ? "'".$mysqli->real_escape_string($_POST['husband'])."'" : NULL;
 
    