【问题标题】:What is equivalent of mysql_insert_id(); using prepared statement?什么相当于 mysql_insert_id();使用准备好的语句?
【发布时间】:2012-04-02 23:13:00
【问题描述】:

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

【问题讨论】:

  • 什么是mysql_insert_id();在准备好的语句样式中?
  • 你的意思是,PDO 库中mysql_insert_id 的等价物是什么? the documentation 有问题吗?

标签: php sql pdo


【解决方案1】:

如果您使用的是 PDO,则为 PDO::lastInsertId()。所以如果你的数据库句柄叫$link:

$order_id = $link->lastInsertId();

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

$order_id = $link->insert_id;

【讨论】:

  • 但我使用准备好的语句和 mysqli 而不是 PDO
  • @user1227124:那就是mysqli::$insert_id 或mysqli_insert_id()。
  • @user1227124:下次,请在文档中查找。我们希望对 SO 问题进行先前的研究。
【解决方案2】:

您可以尝试$stmt->insert_id 获取插入的id

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 2014-09-16
    • 2014-09-19
    相关资源
    最近更新 更多