2012-03-14 60 views
0

可能是一个简单的为你的开发人员那里抓斗从一个表的最后插入的ID添加到另一个表

我有这样的代码插入一个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表中,并且我似乎无法保留插入“订单”表时将创建的相同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>"; 
+0

什么版本的SQL? – 2012-03-14 15:53:18

+0

sqli与准备好的语句 – user1227124 2012-03-14 15:53:57

+0

这看起来很棒,它有什么不对? (问题?) – 2012-03-14 15:54:23

回答

3

我想这是因为无论数据库库您正在使用做一些无效mysql_insert_id(假设它甚至使用mysql功能)。我建议你看看图书馆,找出他们建议你使用什么方法。

1

SQL Server有@@ IDENTITY

它看起来像MySQL有LAST_INSERT_ID();

我的猜测是你正在使用mySQL。如果没有,那么请让我知道版本,以便我可以更新

相关问题