def get_product_by_id(product_id):
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute('SELECT * FROM products WHERE id = %s', (product_id,))
product = cur.fetchone()
cur.close()
if product:
return {'id': product[0], 'name': product[1], 'description': product[2], 'price': product[3], 'image': product[4]}
return None
@app.route('/ecommerce')
def ecommerce():
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute('SELECT id, name, description, price, image FROM products')
products = cur.fetchall()
cur.close()
return render_template('ecom.html', products=products)
@app.route('/add_to_cart/<int:product_id>', methods=['POST'])
def add_to_cart(product_id):
try:
# Retrieve the product information from the database using the get_product_by_id function
product = get_product_by_id(product_id)
if product is None:
return "Product not found."
# Check if the user is logged in
if 'user_id' not in session:
# If the user is not logged in, redirect them to the login page
return redirect(url_for('login'))
# Check if the cart already exists for the user
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM cart WHERE user_id = %s', (session['user_id'],))
cart = cur.fetchone()
if cart is None:
# If the cart does not exist, create a new one
cur.execute('INSERT INTO cart (user_id, product_id, quantity, name, price) VALUES (%s, %s, %s, %s, %s)', (session['user_id'], product['id'], 1, product['name'], product['price']))
mysql.connection.commit()
cart_id = cur.lastrowid
else:
cart_id = cart['id']
# Check if the product is already in the cart
cur.execute('SELECT * FROM cart_items WHERE cart_id = %s AND product_id = %s', (cart_id, product['id']))
cart_item = cur.fetchone()
if cart_item is None:
# If the product is not already in the cart, add it
cur.execute('INSERT INTO cart_items (cart_id, product_id, quantity) VALUES (%s, %s, %s)', (cart_id, product['id'], 1))
else:
# If the product is already in the cart, update the quantity
cur.execute('UPDATE cart_items SET quantity = quantity + 1 WHERE cart_id = %s AND product_id = %s', (cart_id, product['id']))
mysql.connection.commit()
cur.close()
print("Product added to cart successfully.")
return redirect(url_for('ecommerce'))
except Exception as e:
print(f"Error adding product to cart: {e}")
return f"An error occurred while adding the product to the cart: {e}"
This was my code to implement the add to cart function so that i can see the cart in view cart but when i click on add to cart the exception says "An error occurred while adding the product to the cart: 0" i am not able to understand where is the error in the code i just want that whwn i click on add to cart then it should show the product in the view cart webpage