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

use*_*124 10 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) {
Run Code Online (Sandbox Code Playgroud)

什么相当于mysql_insert_id();使用准备好的声明?

Ry-*_*Ry- 21

如果您正在使用PDO,那就是PDO::lastInsertId().因此,如果调用您的数据库句柄$link:

$order_id = $link->lastInsertId();
Run Code Online (Sandbox Code Playgroud)

如果您使用的MySQLi,它mysqli::$insert_id还是mysqli_insert_id():

$order_id = $link->insert_id;
Run Code Online (Sandbox Code Playgroud)