php mysql_id()没有获得最后一次插入

时间:2012-09-21 14:21:07

标签: php mysql-insert-id

我得到了最后一个插入ID的NULL返回,如果有人可以检查我的代码,我将不胜感激。我已经放置了一个id号代替$ result查询,它返回了json echo。我的预感是它与最后一个"}"的位置有关。支架

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);
}*/

2 个答案:

答案 0 :(得分:0)

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

INSERT INTO `lab`.`patients` (`company_id`, `patient_firstname`, `patient_lastname`, `patient_dob`, `patient_added`) VALUES ('$company_id', '$first_name', '$last_name', '$dob', '$updated')

答案 1 :(得分:0)

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