Online Shopping System with Python & SQL
Online Shopping System with Python & SQL
This project is a simple yet useful creation developed by a student to understand how
Python and SQL can work together to make real-life systems like an online shopping
application. The main aim of this project is to show how Python can handle user input and
logic while SQL helps store all the important data safely.
It gave me a good learning experience about coding, databases, and how the two connect
to make a complete working system.
Python Introduction
Python is one of the most popular and beginner-friendly programming languages used today.
It was developed by Guido van Rossum and first released in 1991. It is known for its simple
syntax, readability, and flexibility, making it a great choice for students and professionals
alike. In this project, Python has been used as the main programming language to handle all
logic and operations.
1. Easy to Learn: The syntax is simple and very close to the English language.
2. Versatile: It can be used for web development, data analysis, artificial intelligence,
and automation.
3. Extensive Libraries: Python provides thousands of built-in libraries and modules
that make coding easier.
SQL Introduction
SQL stands for Structured Query Language, and it is used to store, manage, and retrieve
data from databases. In this project, SQL has been used to keep records of products, users,
and their orders. It works as the backbone of the system by handling all the data operations
in a structured and organized way.
1. Data Management: Helps store, update, and retrieve large amounts of data easily.
2. High Security: Provides user access control to keep data safe.
3. Reliability: Ensures data accuracy and consistency even after multiple operation
Project Objectives
The main objective of this project is to create a simple Online Shopping System using
Python and SQL. The idea is to make a small version of an e-commerce platform where
users can view products, select what they want, and place orders — all through Python’s
program interface. The database part, made using SQL, safely stores all product details,
customer data, and order records.
While working on this project, the goal was not just to make a working program but also to
understand how programming and databases work together in real-world applications. It
helped me learn how user data is handled, how queries work in SQL, and how Python can
be connected to a database to make a complete system.
2. To connect Python with SQL and perform database operations easily.
3. To allow users to view, add, and order products using the Python interface.
4. To help the admin manage the database (add, update, or delete products).
5. To understand the concept of data connectivity, query execution, and database
management using Python.
Tools and Technologies Used
This project has been developed using a set of simple yet powerful tools and technologies.
Each tool plays an important role in building and running the Online Shopping System
smoothly. Below is a detailed explanation of the technologies used:
Python is the main programming language used in this project. It handles all the logic of the
system such as displaying products, taking user input, and connecting to the database.
Python is known for its clear syntax and is widely used in web development, automation, and
data analysis.
● Handles operations like adding products, showing data, and placing orders.
MySQL is an open-source relational database used to store and manage all the data of the
project. It stores details such as product information, user data, and orders in well-organized
tables.
MySQL Connector is a Python library that helps to connect the Python program with the
MySQL database. It allows the execution of SQL queries directly from Python code.
For coding and testing the program, IDEs like IDLE and Visual Studio Code (VS Code)
were used. These platforms provide an easy-to-use interface for writing, running, and
debugging Python code.
5. Operating System
The project was developed on Windows 10, but it can also run on Linux or macOS since
Python and MySQL are cross-platform compatible.
This modular structure makes it easy to understand, test, and improve each part of the
project separately. It also ensures that the whole program remains simple, flexible, and easy
to maintain.
1. User Module
The User Module is designed for the customers who use the online shopping system. It
allows users to browse through the list of products, select the items they want to buy, and
place their orders.
In this module, the user interacts directly with the Python interface. The system ensures that
the user experience is easy, smooth, and secure. Users can also register themselves, log in
to their accounts, and check their order history.
Main Functions:
The user module focuses mainly on making the interface friendly and ensuring that all basic
shopping activities can be done easily.
2. Admin Module
The Admin Module is meant for the shop owner or administrator who controls and manages
the overall system. The admin has more power than a normal user. They can add, update, or
delete products, and also check the list of all orders placed by customers.
This module ensures that the store’s data is always up-to-date and accurate. It helps the
admin maintain the website and manage inventory effectively.
Main Functions:
● Add new products to the system with details like name, price, and stock quantity.
The admin module is one of the most important parts of the project because it keeps
everything under control and ensures smooth business operations.
3. Database Module
The Database Module is the backbone of the entire system. It stores and manages all the
data related to users, products, and orders. This module is developed using MySQL, which
is connected to Python through SQL queries.
Whenever a user or admin performs an action—like logging in, adding a product, or placing
an order—the data is stored or retrieved from the database. The database ensures that
information is accurate, secure, and can be accessed quickly when required.
Main Functions:
● Maintain product information including product ID, name, price, and quantity.
● Provide quick data retrieval for Python programs to display results instantly.
The database module acts as a bridge between the user/admin actions and the stored
information. It makes sure that every part of the system works properly and that data is
always safe and organized.
This modular division makes the Online Shopping System more structured, efficient, and
easy to use. Each module works together to create a smooth online shopping experience for
both customers and administrators.
Database Design
The database of this project is designed using MySQL, which is a popular relational
database management system. It helps to store, manage, and retrieve data efficiently. A
well-designed database is an essential part of any system because it ensures that the
information is organized and can be accessed quickly and accurately.
In this project, the database mainly stores information about the users who use the system
and the products that are managed within the system. The design focuses on simplicity,
clarity, and easy management, which is suitable for a student-level project.
The users table contains all the information about the users of the system. This table is
important because it allows the system to identify each user uniquely and provide
user-specific functionality like login and cart management.
1. id → A unique number assigned to each user. This is the primary key and
ensures that each user can be distinguished from others.
3. email → Email of the user, which is also used for login purposes.
● Purpose:
The users table allows the system to store individual user data securely and
supports login and account-related operations.
The products table stores all the information about the products in the system. Every
product has specific details like name, price, category, and an image.
1. id → A unique number assigned to each product. This is the primary key and
is set to auto-increment so that new products get unique IDs automatically.
● Purpose:
The products table organizes all product information in one place. It allows the
system to display products, filter them by category or price, and manage
product details efficiently.
Although the database currently has only two main tables (users and products), the
system also handles a cart functionality, which links users and products.
This creates a one-to-many relationship from the perspective of the user to products. The
relationship allows the system to track which products are selected by which users and
helps in managing operations like adding, removing, or updating items in the cart.
SQL Connectivity and How SQL Works with Python
In this project, SQL connectivity is one of the most important parts because it helps in
connecting the database with the Python program. Without SQL connectivity, the data stored
in the database would remain separate from the Python application, and the system would
not be able to work properly. By establishing this connection, we make sure that the data can
move smoothly between the program and the database whenever required.
Python is mainly used for performing logical operations and user interaction, while SQL
(Structured Query Language) is used for storing, organizing, and managing the data.
When these two work together, it becomes easy to build a complete working system where
data can be saved, updated, deleted, or retrieved in just a few seconds.
The database is created using MySQL, which is a very popular and easy-to-use database
management system. It stores all the information related to users and products in the form of
tables. Each table has rows and columns, just like an Excel sheet, where each row
represents a record and each column represents a field or attribute. Python can easily
connect to this database using the SQL connectivity feature and perform operations on
these tables.
The main purpose of using SQL connectivity in this project is to allow communication
between Python and MySQL. It helps in sending commands from Python to SQL and
getting the required data back. For example, when we want to see all the products available,
Python sends a command to MySQL saying, “Show me all the products,” and MySQL replies
with a list of all the product names, prices, and details stored in the database.
Through this connection, the system can perform all CRUD operations —
C for Create,
R for Read,
U for Update, and
D for Delete.
These are the four main functions of any database, and they help in keeping the system
active and responsive. Python acts as the middle layer that takes the user’s input and
passes it to SQL, then takes the response from SQL and shows it to the user in a readable
format.
When the project starts running, Python first tries to connect to the MySQL database using
certain credentials like hostname, username, password, and database name. Once the
connection is successful, Python gets full access to the tables stored in that database.
If a user wants to add a new product or record, Python sends an INSERT command to SQL.
If a user wants to view all records, Python sends a SELECT command.
If the user updates a product price or name, Python sends an UPDATE command.
And if the user removes a product, Python sends a DELETE command.
This process happens automatically in the background without the user needing to
understand SQL. The Python program handles everything with the help of SQL connectivity.
It makes the project more interactive and gives it a real-life working experience, just like how
online stores or data-management systems work.
2. SQL to Python: SQL processes the query and sends the result back.
This back-and-forth process is what keeps the system functional and efficient.
#!/usr/bin/env python3
import [Link]
def db_conn():
return [Link](
)
# ---- Helpers ----
def money(x):
try:
except Exception:
return str(x)
def to_dec(v):
def color_for_id(pid):
def hue_to_rgb(p,q,t):
if t < 0: t += 1
if t > 1: t -= 1
return p
if S == 0: r = g = b = L
else:
p=2*L-q
return f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}"
bg = color_for_id(pid)
r = int(hexcol[1:3],16); g = int(hexcol[3:5],16); b =
int(hexcol[5:7],16)
return f"#{r:02x}{g:02x}{b:02x}"
bg2 = darken(bg)
</svg>'''
def db_list_categories(conn):
cur = [Link]()
[Link]()
return cats
params = []
if cats:
[Link](cats)
if mn is not None:
if mx is not None:
cur = [Link](dictionary=True)
[Link](sql, tuple(params))
rows = [Link]()
[Link]()
return rows
cur = [Link](dictionary=True)
cur = [Link]()
next_id = [Link]()[0]
[Link]()
[Link]()
return next_id
SESSIONS = {}
def nav_html(sess):
if [Link]("user"):
u = sess["user"]
cat_checks = [
f'<label><input type="checkbox" name="category"
value="{[Link](c)}" {"checked" if c in selected_cats else ""}>
{[Link](c)}</label>'
for c in categories
prod_cards = []
for p in products:
if [Link]("user"):
add_block = f'''
</form>
'''
else:
add_block = f'''
<a class="btn-disabled"
href="/login?next={urlquote('/')}">add to cart</a>
'''
prod_cards.append(f'''
<div class="card">
<img class="thumb" src="{src}"
alt="{[Link](p['name'])}">
<div class="name">{[Link](p['name'])}</div>
<div class="price">₹{money(p['price'])}</div>
{add_block}
</div>
''')
cart_rows = []
for it in cart_items:
cart_rows.append(f'''
<tr>
<td>{[Link](it["name"])}</td>
<td>₹{money(it["price"])}</td>
<td>{it["quantity"]}</td>
<td>₹{money(it["line_total"])}</td>
<td><a
href="/remove?product_id={it["product_id"]}">Remove</a></td>
</tr>
''')
msg_html = f'<div class="msg">{[Link](msg)}</div>' if
(msg and msg != "ordered") else ""
<html>
<head>
<title>Shop</title>
<style>
* {{ box-sizing: border-box; }}
h1 {{ margin: 0 0 12px; }}
.price {{ font-weight:700; }}
#[Link] {{ display:flex; }}
</style>
</head>
<body>
<h1>Shop</h1>
{nav_html(sess)}
{msg_html}
<div class="layout">
<aside class="filters">
<h3>Filters</h3>
<div class="group">
<strong>Categories</strong>
</div>
<div class="group">
<strong>Price</strong>
</div>
<div class="row">
<button type="submit">Apply</button>
</div>
</form>
</aside>
<main>
<div class="grid">
</div>
</main>
</div>
<div id="overlay">
<header>
<strong>Your Cart</strong>
</header>
<div class="body">
<table>
<tr><th>Product</th><th>Price</th><th>Qty</th><th>Line</th><th>
</th></tr>
{''.join(cart_rows) if cart_rows else '<tr><td
colspan="5"><em>Cart is empty</em></td></tr>'}
<tr><td colspan="3"
style="text-align:right"><strong>Total</strong></td><td
colspan="2"><strong>₹{money(cart_total)}</strong></td></tr>
</table>
</div>
</div>
</div>
<script>
(function(){{
[Link]('click', function() {{
[Link]('show'); }});
// show success alert after checkout
[Link]('msg');
}}
}})();
</script>
</body>
</html>'''
<body>
<h1>{[Link](title)}</h1>
{err}
{name_field}
{hidden_next}
<div><button type="submit">{[Link](title)}</button></div>
</form>
<p><a href="/">Back</a></p>
</body></html>'''
class Handler(BaseHTTPRequestHandler):
new_cookie = None
def get_session(self):
sid = secrets.token_hex(16)
def set_cookie_if_new(self):
if self.new_cookie:
self.send_header("Set-Cookie", self.new_cookie)
self.new_cookie = None
body = html_text.encode("utf-8")
self.send_response(status)
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.set_cookie_if_new()
self.end_headers()
[Link](body)
body = svg_text.encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "image/svg+xml;
charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.set_cookie_if_new()
self.end_headers()
[Link](body)
self.send_response(303)
self.send_header("Location", location)
self.set_cookie_if_new()
self.end_headers()
def parse_post(self):
length = int([Link]("Content-Length", "0") or "0")
def do_GET(self):
parsed = urlparse([Link])
path = [Link]
qs = parse_qs([Link])
try:
conn = db_conn()
except Exception as e:
self.send_html(f"<h1>DB
Error</h1><p>{[Link](str(e))}</p>", 500)
return
try:
if path == "/":
categories = db_list_categories(conn)
selected_cats = qlist("category")
products = db_list_products(
conn, categories=selected_cats,
min_price=qstr("min_price"),
max_price=qstr("max_price")
items = []
total = Decimal("0.00")
count = 0
page = render_index(
min_price=qstr("min_price"),
max_price=qstr("max_price"),
cart_items=items, cart_total=total, cart_count=count,
msg=qstr("msg")
if path == "/signup":
self.send_html(render_auth("Sign up",
f"/signup?next={[Link](next_url)}", next_url=next_url))
[Link](); return
if path == "/login":
self.send_html(render_auth("Log in",
f"/login?next={[Link](next_url)}", next_url=next_url))
[Link](); return
if path == "/logout":
sess["user"] = None
# Require login
if not [Link]("user"):
[Link]("/login?next=" + urlquote([Link]));
[Link](); return
try:
except ValueError:
[Link]("/?msg=Invalid+input"); [Link]();
return
[Link]("/?msg=Invalid+input"); [Link]();
return
if not prod:
[Link]("/?msg=Product+not+found");
[Link](); return
[Link]("/?msg=Added+to+cart"); [Link]();
return
if path == "/remove":
if not [Link]("user"):
[Link]("/login?next=" + urlquote([Link]));
[Link](); return
try:
except ValueError:
[Link]("/?msg=Invalid+input"); [Link]();
return
if pid in sess["cart"]:
del sess["cart"][pid]
[Link]("/?msg=Removed")
else:
[Link]("/?msg=Item+not+in+cart")
[Link](); return
if path == "/checkout":
if not [Link]("user"):
[Link]("/login?next=/checkout"); [Link]();
return
if not sess["cart"]:
[Link]("/?msg=Cart+is+empty"); [Link]();
return
if [Link]("/img/"):
try:
pid = int(id_str)
except ValueError:
if not prod:
self.send_svg(svg_card(prod["name"], prod["price"],
prod["id"], w=w, h=h)); [Link](); return
try: [Link]()
except: pass
self.send_html(f"<h1>Error</h1><pre>{[Link](str(e))}</pre>",
500)
def do_POST(self):
parsed = urlparse([Link])
path = [Link]
qs = parse_qs([Link])
try:
conn = db_conn()
except Exception as e:
self.send_html(f"<h1>DB
Error</h1><p>{[Link](str(e))}</p>", 500)
return
try:
if path == "/signup":
form = self.parse_post()
self.send_html(render_auth("Sign up",
f"/signup?next={[Link](next_url)}", "All fields required",
next_url)); [Link](); return
if db_find_user_by_email(conn, email):
self.send_html(render_auth("Sign up",
f"/signup?next={[Link](next_url)}", "Email already in use",
next_url)); [Link](); return
if path == "/login":
form = self.parse_post()
self.send_html(render_auth("Log in",
f"/login?next={[Link](next_url)}", "Invalid email or
password", next_url)); [Link](); return
except Exception as e:
try: [Link]()
except: pass
self.send_html(f"<h1>Error</h1><pre>{[Link](str(e))}</pre>",
500)
print(f"Serving on [Link]
httpd.serve_forever()
if __name__ == "__main__":
run()
SQL Code
CREATE DATABASE ecomshop;
name VARCHAR(50),
email VARCHAR(100),
password VARCHAR(100)
);
image_url VARCHAR(255),
price DECIMAL(10,2),
category VARCHAR(50)
);
('Herbal Shampoo',
'[Link] 125.99, 'Beauty
and Personal Care'),
('Face Moisturizer',
'[Link] 128.49, 'Beauty
and Personal Care'),
('Perfume Spray',
'[Link]
pg', 315.00, 'Beauty and Personal Care'),
('Wireless Earbuds',
'[Link]
=1727669669', 149.99, 'Electronics'),
('Smartwatch',
'[Link]
pg', 279.99, 'Electronics'),
('Bluetooth Speaker',
'[Link]
-9138-0bd90874391e_1300x.png?v=1709717442', 129.99, 'Electronics'),
('Men T-Shirt',
'[Link]
th=800', 312.99, 'Fashion and Apparel'),
('Pasta Pack',
'[Link]
, 12.99, 'Food'),
('Organic Honey',
'[Link]
g', 216.49, 'Food'),
('Energy Drink',
'[Link]
', 211.99, 'Beverages'),
('Wooden Chair',
'[Link]
, 139.00, 'Beverages');
How the Code Works Behind the System
The project is a mini e-commerce web application developed using Python and
MySQL. It demonstrates the integration of a programming language with a
database to manage users, products, and transactions in a web-based
environment. This explanation covers the interaction between Python and
SQL, user session management, product display, cart functionality, and
checkout operations.
SQL handles permanent storage and retrieval of data, while Python handles
application logic, computation, and dynamic display to users.
5. It dynamically generates HTML with the product and cart information.
This ensures that users always see up-to-date data on the website.
● The cart modal shows product details, quantity, price, line total, and
total cart amount.
Python updates the cart and reflects changes instantly in the user interface.
5. Checkout Process
The checkout process simulates order placement:
Although no actual order is stored in the database, this flow simulates a real
e-commerce checkout experience.
1.
2.
3.
4.
Cursors in Python ([Link]()) execute these queries and fetch results. Transactions
are committed using [Link]() for permanent changes.
7. Error Handling and Data Security
The system includes multiple safeguards:
● Prices and quantities are validated using Python’s Decimal module for
precision.