doukao8851 2012-03-14 15:51
浏览 22
已采纳

从一个表中获取最后一个插入ID以放入另一个表中

probably a simple one for you developers out there

I have this code to insert an order_id and order_name into the 'orders' table:

<?php
// start the session handler
require_once('dbfunction.php');

//connect to database
$conn = DB();

require_once('header.php');

//should we process the order?
if (isset($_POST['process'])) {

$order_name = $_POST['order_name'];

//create initial order
$stmt = $conn2->prepare("INSERT INTO orders (order_name) VALUES (?)");

//bind the parameters
    $stmt->bind_param('s', $order_name);

    // Execute query
    $stmt->execute();

I now want to insert the order items into the order_items table and I cant seem to keep that same ID that was created when inserting into the 'orders' table and add it to the 'order_items' table along with the order_items. Here is my code:

//this gets the most recent auto incremented ID from the database - this is the order_id we have just created
$order_id = mysql_insert_id();

//loop over all of our order items and add to the database
foreach ($_SESSION['order'] as $item) {

  $prod_id = $item['prod_id'];
  $quantity = $item['quantity'];
  $prod_type = $item['prod_type'];

  $stmt = $conn2->prepare("INSERT INTO order_items (order_id, prod_id, quantity, prod_type) VALUES (?, ?, ?, ?)");

  //bind the parameters
    $stmt->bind_param('iiis', $order_id, $prod_id, $quantity, $prod_type);

    // Execute query
    $stmt->execute();
}

    echo "<p class='black'>Order Processed</p>";
  • 写回答

2条回答 默认 最新

  • doucuo4413 2012-03-14 15:53
    关注

    I would guess it's because whatever database library you are using is doing something to invalidate the mysql_insert_id (assuming it's even using the mysql functions). I'd suggest you look into the library to find out what method they suggest you use instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀