Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have used prepared statement to insert an order into an orders table but now I want to insert the order items into the order items table based on the last ID inserted in the orders table:

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

What is equivalent to mysql_insert_id(); using prepared statement?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
672 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you're using PDO, it's PDO::lastInsertId(). So if your database handle is called $link:

$order_id = $link->lastInsertId();

If you're using MySQLi, it's mysqli::$insert_id or mysqli_insert_id():

$order_id = $link->insert_id;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...