-2

I have this multiple record insert. I need to get last id from product and loan table insert to table import. How can I doing that?

This is my code:

$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);
Machavity
  • 30,841
  • 27
  • 92
  • 100
Ab Le
  • 65
  • 1
  • 1
  • 7

1 Answers1

2
  1. There is no such thing as a "multiple insert". Each insert have to be performed separately. Especially if you need an insert id from each query.
  2. All insert queries must be executed using prepared statements.

Here is your code written properly

$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;
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • 2
    It should be noted that in order for [`last_insert_id()`](https://www.php.net/manual/en/mysqli.insert-id.php) to work, that each of the tables must contain an auto_increment'ed column. – Funk Forty Niner Dec 12 '19 at 15:13