【问题标题】:Grab the last insert id from one table to put into another table从一个表中获取最后一个插入 id 以放入另一个表
【发布时间】:2012-03-14 15:51:12
【问题描述】:

对于您的开发人员来说可能是一个简单的

我有这段代码可以将 order_id 和 order_name 插入到“订单”表中:

<?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();

我现在想将订单项插入 order_items 表,但我似乎无法保留插入“orders”表时创建的相同 ID,并将其与 order_items 一起添加到“order_items”表中。这是我的代码:

//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>";

【问题讨论】:

  • 带有准备好的语句的sqli
  • 看起来不错,有什么问题吗? (问题?)
  • VERSION MYSQLi 如果那是一个版本:s
  • 我发现你是这样做的:$order_id = mysqli_insert_id($conn2);谢谢你们的灵感!

标签: php sql prepared-statement shopping-cart


【解决方案1】:

我猜这是因为您使用的任何数据库库都会使mysql_insert_id 无效(假设它甚至使用mysql 函数)。我建议您查看该库以了解他们建议您改用什么方法。

【讨论】:

    【解决方案2】:

    SQL Server 有@@IDENTITY

    看起来 mySQL 有 LAST_INSERT_ID();

    我猜你正在使用 mySQL。如果没有,请告诉我版本,以便我更新

    【讨论】:

      猜你喜欢
      • 2011-03-06
      • 2023-03-16
      • 2011-04-30
      • 2011-05-07
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多