什么相当于mysql_insert_id();使用预备声明?

时间:2012-03-17 21:05:52

标签: php sql pdo

我已使用预准备语句将订单插入订单表,但现在我想根据订单表中插入的最后一个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();

2 个答案:

答案 0 :(得分:19)

如果您使用的是PDO,则为PDO::lastInsertId()。因此,如果您的数据库句柄被称为$link

$order_id = $link->lastInsertId();

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

$order_id = $link->insert_id;

答案 1 :(得分:3)

您可以尝试使用$stmt->insert_id来插入ID