我有这个多条记录插入。我需要从product
和loan
表插入表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);
答案 0 :(得分: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;