从多个插入中获取最后一个ID

时间:2019-12-12 14:30:35

标签: php mysql mysqli insert id

我有这个多条记录插入。我需要从productloan表插入表import中获取最后一个ID。我该怎么办?

这是我的代码:

$sql = "INSERT INTO `product` (`product_id`, `barcode`, `delete`,   `id_list_name`) VALUES (NULL, '".$barcode."', '0', '".$listnameid."');
        INSERT INTO `loan` (`loan_id`, `date`, `Quantity`, `delete`, `id_user`) VALUES (NULL, '".date("Y-m-d")."', '1', '0', '".$userid."');
        INSERT INTO `import` (`import_id`, `id_product`, `date`, `delete`, `date delete`, `id_user`, `id_loan`) VALUES (NULL, '4', '".date("Y-m-d")."', '0', '', '".$userid."', '"4"');
       ";
        mysqli_query($conn, $sql);

1 个答案:

答案 0 :(得分:2)

  1. 没有“多次插入”之类的东西。每个插入必须分别执行。特别是如果您需要每个查询的插入ID。
  2. 所有插入查询必须使用准备好的语句执行。

这是您编写的代码正确

$sql = "INSERT INTO `product` (`product_id`, `barcode`, `delete`,   `id_list_name`) VALUES (NULL, ?, '0', ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $barcode,$listnameid);
$product_id = $conn->insert_id;

$sql = "INSERT INTO `loan` (`loan_id`, `date`, `Quantity`, `delete`, `id_user`) VALUES (NULL, CURDATE(), '1', '0', ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $userid);
$loan_id = $conn->insert_id;

$sql = "INSERT INTO `import` (`import_id`, `id_product`, `date`, `delete`, `date delete`, `id_user`, `id_loan`) VALUES (NULL, ?, CURDATE(), '0', '', ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $product_id, $userid, $loan_id;);
$import_id = $conn->insert_id;