2012-03-14 125 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。如果沒有,那麼請讓我知道版本,以便我可以更新

相關問題