Daos

 avatar
unknown
plain_text
5 months ago
2.0 kB
1
Indexable
package DAOs;

import DBConnection.DBConnection;
import Models.CartItem;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CartItemDAO {
    public static List<CartItem> getCartItemsByUserId(int userId) {
        List<CartItem> cartItems = new ArrayList<>();
        String query = "SELECT * FROM cart_items WHERE user_id = ?";

        try (Connection conn = DBConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
             
            stmt.setInt(1, userId);
            ResultSet rs = stmt.executeQuery();
            
            while (rs.next()) {
                int cart_item_id = rs.getInt("cart_item_id");
                int product_id = rs.getInt("product_id");
                int product_option_id = rs.getInt("product_option_id");
                int quantity = rs.getInt("quantity");

                // Truy vấn để lấy thông tin giá và tên sản phẩm
                String productQuery = "SELECT price, name FROM products WHERE product_id = ?";
                try (PreparedStatement productStmt = conn.prepareStatement(productQuery)) {
                    productStmt.setInt(1, product_id);
                    ResultSet productRs = productStmt.executeQuery();
                    
                    double product_price = 0.0;
                    String product_name = "";
                    
                    if (productRs.next()) {
                        product_price = productRs.getDouble("price");
                        product_name = productRs.getString("name");
                    }

                    CartItem item = new CartItem(cart_item_id, userId, product_id, product_option_id, quantity, product_price, product_name);
                    cartItems.add(item);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return cartItems;
    }
}
Editor is loading...
Leave a Comment