0

我得到最后一个插入 ID 的 NULL 返回,如果有人可以检查我的代码,我将不胜感激。我放置了一个 ID 号来代替 $result 查询,它返回 json 回显。我的预感是它与最后一个“}”括号的位置有关。

if (empty($_POST) === false) {
$update_data = array(
      'company_id'              => $_POST['company_id'],
      'addpatient_firstname'    => $_POST['addpatient_firstname'],
      'addpatient_lastname'     => $_POST['addpatient_lastname'],
      'addpatient_dob'          => $_POST['addpatient_dob'],
      'patient_added'           => $_POST['patient_added']
    );


    $required_fields = array('company_id', 'addpatient_firstname', 'addpatient_lastname', 'addpatient_dob', 'patient_added');
    foreach($update_data as $key=>$value) {
        if (empty($value) && in_array($key, $required_fields) === true) {
            $errors[] = 'Fields marked with an asterisk are required';
            break 1;
        }
    }
}

if (empty($_POST) === false && empty($errors) === true) {

      $company_id   = $_POST['company_id'];
      $patient_id   = $_POST['addpatient_id'];
      $first_name   = $_POST['addpatient_firstname'];
      $last_name    = $_POST['addpatient_lastname'];
      $dob          = $_POST['addpatient_dob'];
      $updated      = $_POST['patient_added'];


      $update = array();
      array_walk($update_data, 'array_sanitize');

      foreach($update_data as $field=>$data) {
          $update[] = '`' . $field . '` = \'' . $data . '\'';
      }

      mysql_query("INSERT INTO `lab`.`patients` (`company_id`, `patient_id`, `patient_firstname`, `patient_lastname`, `patient_dob`, `patient_added`) VALUES ('$company_id', NULL, '$first_name', '$last_name', '$dob', '$updated')");
      $last_patient_id = mysql_insert_id();

      $result = mysql_query("SELECT `patient_id`, `patient_firstname`, `patient_lastname`, `patient_dob` FROM `patients` WHERE `patient_id` = $last_patient_id");

      $data[] = mysql_fetch_assoc($result);
}

      echo json_encode( $data );

/*        exit();

} else if (empty($errors) === false) {
echo output_errors($errors);
}*/
4

2 回答 2

0

我在 www.php.net 中看到 mysql_insert_id() 仅适用于自动递增的列。你的主键怎么样?

于 2012-09-21T14:33:07.483 回答
0

如果patient_id是 auto_increment 字段,那么您应该将此字段留在插入语句之外,而不是插入NULL.

INSERT INTO `lab`.`patients` (`company_id`, `patient_firstname`, `patient_lastname`, `patient_dob`, `patient_added`) VALUES ('$company_id', '$first_name', '$last_name', '$dob', '$updated')
于 2012-09-21T14:32:22.740 回答