2012-03-17 66 views
8

我用事先準備好的聲明中插入一個訂單到訂單表,但現在我想的訂單項目插入基礎上插入訂單表中的最後一個ID的訂單項目表:什麼是mysql_insert_id();使用準備好的語句

if (isset($_POST['process'])) { 

    $order_name = $_POST['order_name']; 
    //create initial order 
    $stmt = $conn2->prepare("INSERT INTO orders (order_name) VALUES (?)"); 
    $stmt->bind_param('s', $order_name); 
    $stmt->execute(); 

    //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) { 

什麼是等價到mysql_insert_id();使用預處理語句?

+0

什麼是你的問題? – 2012-03-17 21:08:30

+0

什麼是mysql_insert_id();在準備好的陳述風格? – user1227124 2012-03-17 21:09:54

+1

你的意思是,PDO庫中的'mysql_insert_id'等價於什麼? [文檔]有問題(http://www.php.net/manual/en/pdo.lastinsertid.php)? – 2012-03-17 21:17:49

回答

17

如果您使用PDO,它是PDO::lastInsertId()。所以,如果你的數據庫手柄稱爲$link

$order_id = $link->lastInsertId(); 

如果您使用的MySQLi,這是mysqli::$insert_idmysqli_insert_id()

$order_id = $link->insert_id; 
+0

但即時通訊使用準備好的語句與mysqli不PDO – user1227124 2012-03-17 21:10:58

+0

@ user1227124:然後它是['mysqli :: $ insert_id'](http://php.net/manual/en/mysqli.insert-id.php)或'mysqli_insert_id( )'。 – Ryan 2012-03-17 21:12:38

+0

感謝它的工作! – user1227124 2012-03-17 21:17:49

2

你可以嘗試$stmt->insert_id得到插入ID