我如何使用lastInsertId从另一个表中插入值

发布于 2025-01-31 17:26:42 字数 1173 浏览 2 评论 0原文

因此,我有两个表订单_manager和订单。 目标是将订单_ID从订单管理器插入user_order表中。

我不确定在这种情况下如何在控制器中使用变量$ order_id。我想尝试使用插入式插入,因为我认为这将是最好的解决方案。但是,仍然无法缠绕我如何在控制器中获取其价值。

这是我的控制器,

  
    if($artworks -> confirm_order($full_name,$phone,$address,$email));{//this table has a primary key of order_id thats auto increments
    foreach($_SESSION['cart'] as $key => $values)

  {     
        $title=$values['title'];
        $price=$values['price'];
        $quantity=$values['quantity'];
        $artworks -> new_user_order(/*$order_id,*/$title,$price,$quantity);//foreign key of order_id
  }
    unset($_SESSION['cart']);
    }

这是我的模型

    public function new_user_order($order_id,$title,$price,$quantity){
        
        $sql = "INSERT INTO user_orders(order_id,title,price,quantity) VALUES(?,?,?,?)";
        $stmt = $this->connect()->prepare($sql);
        $stmt->execute([$order_id,$title,$price,$quantity]);
        //$order_id = $this->connect()->LastInsertId();
        header("location: {$_SERVER['HTTP_REFERER']}");
    }

So I have two tables order_manager and order.
The goal is to insert the order_id from order manager into the user_order table.

Im unsure how to use the variable $order_id in my controller in this scenario. Ive attempted using the InsertLastId as i thought this would be the best solution. But still cant wrap my head around how I can grab its value in the controller.

Here's my Controller

  
    if($artworks -> confirm_order($full_name,$phone,$address,$email));{//this table has a primary key of order_id thats auto increments
    foreach($_SESSION['cart'] as $key => $values)

  {     
        $title=$values['title'];
        $price=$values['price'];
        $quantity=$values['quantity'];
        $artworks -> new_user_order(/*$order_id,*/$title,$price,$quantity);//foreign key of order_id
  }
    unset($_SESSION['cart']);
    }

here's my model

    public function new_user_order($order_id,$title,$price,$quantity){
        
        $sql = "INSERT INTO user_orders(order_id,title,price,quantity) VALUES(?,?,?,?)";
        $stmt = $this->connect()->prepare($sql);
        $stmt->execute([$order_id,$title,$price,$quantity]);
        //$order_id = $this->connect()->LastInsertId();
        header("location: {$_SERVER['HTTP_REFERER']}");
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鲸落 2025-02-07 17:26:42

我相信正确的方法将是

$order_id = $stmt->insert_id;

I believe the correct way to do it would be

$order_id = $stmt->insert_id;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文