Home Blog Page 97

Introduction to Java, Features & Setup (JDK, JRE, JVM)

0
java spring boot course
java spring boot course

Table of Contents

  1. What is Java?
  2. A Brief History of Java
  3. Key Features of Java
  4. Java Terminologies: JDK, JRE, and JVM
  5. Java Compilation & Execution Process
  6. Installing Java (JDK) on Your System
  7. Verifying Java Installation
  8. Writing Your First Java Program
  9. Summary and What’s Next?

1. What is Java?

Java is a high-level, object-oriented, class-based programming language that is designed to have as few implementation dependencies as possible. Developed by James Gosling at Sun Microsystems in 1995 (later acquired by Oracle), Java has become one of the most popular programming languages for building enterprise-scale applications, web backends, Android apps, and more.

Its write once, run anywhere capability makes it platform-independent and ideal for distributed computing.


2. A Brief History of Java

Java was initially developed as part of the Green Project at Sun Microsystems and was originally called Oak. It was later renamed Java after the Java coffee from Indonesia. The first public release was in 1995, and since then, it has gone through multiple versions and updates.

Notable milestones include:

  • Java 1.0 (1995): Initial release
  • Java 5 (2004): Introduced generics, annotations, and enums
  • Java 8 (2014): Lambda expressions, Streams API
  • Java 17 (2021): Long-Term Support (LTS)
  • Java 21 (2023): Latest LTS version (as of this writing)

3. Key Features of Java

  • Platform Independent: Write once, run anywhere (via the JVM)
  • Object-Oriented: Everything is treated as an object
  • Robust: Strong memory management, exception handling
  • Secure: Built-in security features like bytecode verification
  • Multithreaded: Supports concurrent execution of threads
  • High Performance: Just-In-Time (JIT) compiler for faster execution
  • Dynamic and Extensible: Supports loading classes dynamically at runtime
  • Portable: Bytecode can run on any platform with a JVM

4. Java Terminologies: JDK, JRE, JVM

JDK (Java Development Kit)

It is a software development kit that includes tools for developing Java applications:

  • javac (Java compiler)
  • java (Java interpreter)
  • JRE and development tools

JRE (Java Runtime Environment)

It provides the environment required to run Java applications. It contains:

  • JVM
  • Core libraries

Note: JRE does not include development tools like the compiler.

JVM (Java Virtual Machine)

The heart of Java’s platform independence. JVM:

  • Executes the bytecode
  • Provides abstraction from the underlying hardware
  • Is different for every OS but runs the same bytecode

5. Java Compilation & Execution Process

Source Code (.java)

Compilation by javac

Bytecode (.class)

Executed by JVM

This process allows Java code to be platform-independent as the same .class file can run on any OS with the corresponding JVM.


6. Installing Java (JDK) on Your System

For Windows:

  1. Download the JDK from the Oracle website.
  2. Run the installer and follow the setup steps.
  3. Set the JAVA_HOME environment variable.
  4. Add JAVA_HOME\bin to your system PATH.

For macOS:

brew install openjdk

Then link it:

sudo ln -sfn /opt/homebrew/opt/openjdk/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk

For Linux:

sudo apt update
sudo apt install openjdk-17-jdk

7. Verifying Java Installation

After installation, open your terminal or command prompt and run:

java -version
javac -version

If properly installed, you’ll see version numbers for both.


8. Writing Your First Java Program

Here’s a simple “Hello, World!” in Java:

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

To Compile:

javac HelloWorld.java

To Run:

java HelloWorld

9. Summary and What’s Next?

In this module, you learned:

  • What Java is and why it’s popular
  • Java’s platform-independent architecture
  • The difference between JDK, JRE, and JVM
  • How to install Java and run a simple program

Connectivity Graphs and Constraints: Modeling Hardware Limitations in Quantum Circuits

0

Table of Contents

  1. Introduction
  2. What Is a Connectivity Graph?
  3. Why Connectivity Constraints Matter
  4. Qubit Coupling in Real Quantum Hardware
  5. Representing Hardware with Graphs
  6. Types of Hardware Topologies
  7. IBM’s Grid and Coupling Map
  8. Rigetti’s Lattice Structure
  9. IonQ’s Fully Connected Model
  10. Using NetworkX to Visualize Connectivity
  11. Mapping Circuits to Connectivity Graphs
  12. Effects of Constraints on Circuit Depth
  13. Role of SWAP Gates in Overcoming Constraints
  14. Logical vs Physical Qubit Mapping
  15. Connectivity-Aware Transpilation
  16. Measuring Connectivity Overhead
  17. Coupling-Aware Gate Scheduling
  18. Real Hardware Examples and Benchmarking
  19. Tools and Libraries Supporting Connectivity Modeling
  20. Conclusion

1. Introduction

Connectivity graphs describe how qubits on a quantum device can interact. Understanding and modeling these constraints is critical for building realistic and efficient quantum programs.

2. What Is a Connectivity Graph?

A graph \( G = (V, E) \), where:

  • \( V \): qubits
  • \( E \): allowed two-qubit interactions

3. Why Connectivity Constraints Matter

  • Not all qubits can interact directly
  • Two-qubit gate locations must respect the coupling graph
  • SWAPs may be needed for non-adjacent qubits

4. Qubit Coupling in Real Quantum Hardware

Devices differ in qubit topology:

  • IBM: grid topology
  • Rigetti: lattice
  • IonQ: full connectivity

5. Representing Hardware with Graphs

Edges define which qubits are connected:

coupling_map = [(0,1), (1,2), (2,3)]

6. Types of Hardware Topologies

  • Line (linear chain)
  • Ring
  • 2D Grid
  • Tree
  • All-to-All

7. IBM’s Grid and Coupling Map

IBM uses rectangular grids:

backend.configuration().coupling_map

8. Rigetti’s Lattice Structure

Structured like a square lattice with nearest-neighbor couplings.

9. IonQ’s Fully Connected Model

Any qubit can interact with any other without SWAPs. Ideal for short circuits but slower gate times.

10. Using NetworkX to Visualize Connectivity

import networkx as nx
G = nx.Graph()
G.add_edges_from(coupling_map)
nx.draw(G, with_labels=True)

11. Mapping Circuits to Connectivity Graphs

Analyze if a 2-qubit gate exists between nodes:

  • If not, insert SWAPs
  • Respect physical qubit layout

12. Effects of Constraints on Circuit Depth

Non-local operations increase:

  • Gate depth
  • Total execution time
  • Cumulative error

13. Role of SWAP Gates in Overcoming Constraints

SWAPs help move qubit states to adjacent physical locations, allowing non-local gates to execute.

14. Logical vs Physical Qubit Mapping

  • Logical: from algorithm
  • Physical: actual hardware qubit index
    Transpiler handles the mapping:
transpile(circuit, backend)

15. Connectivity-Aware Transpilation

Transpilers reorder and optimize gates for minimal constraint violations:

  • Qiskit uses SABRE layout
  • t|ket> uses routing and rebase passes

16. Measuring Connectivity Overhead

Compare:

  • Initial vs final depth
  • Number of SWAPs
  • Logical vs physical layout distance

17. Coupling-Aware Gate Scheduling

Smart scheduling can reduce idle time and parallelize allowable gates.

18. Real Hardware Examples and Benchmarking

  • IBM’s 127-qubit Eagle: 2D lattice
  • Rigetti Aspen-M: triangular lattice
  • IonQ: slower but fully connected

19. Tools and Libraries Supporting Connectivity Modeling

  • Qiskit: coupling_map, transpiler visualization
  • t|ket>: placement and routing
  • NetworkX: topology modeling and layout

20. Conclusion

Connectivity graphs define the physical limitations of quantum devices and shape how quantum algorithms are compiled. Understanding these constraints allows developers to optimize performance and execute algorithms efficiently on current hardware.

.

Deploying PHP Applications

0
php course
php course

Table of Contents

  • Introduction to Deployment
  • Preparing Your PHP Application for Deployment
  • Choosing a Hosting Provider
  • Setting Up a Web Server for PHP
  • Deploying on Shared Hosting vs. VPS
  • Deploying with FTP/SFTP
  • Setting Up and Configuring a Database
  • Ensuring Security Before Deployment
  • Continuous Deployment with Git
  • Conclusion

Introduction to Deployment

Once you’ve completed building a PHP application, the next crucial step is to deploy it to a live server. Deployment is the process of transferring your application files to a web server and configuring the server to make the application accessible over the internet. This process involves various considerations like server setup, database integration, and security configurations.

In this module, we will cover the steps to deploy a PHP application and ensure it runs smoothly in a production environment. You will learn how to choose a hosting provider, prepare your application, and deploy it using different methods.


Preparing Your PHP Application for Deployment

Before deploying your PHP application, it’s essential to prepare it for production. Here are some key steps you should follow:

  1. Environment Configuration:
    • Set the environment configuration to production by editing your configuration files. For example, in a .env file, change the environment to production.Disable debugging features (e.g., display_errors) in the PHP configuration.
    ini_set('display_errors', 0); // Disable error display in production error_reporting(E_ALL); // Log all errors, but don't display them
  2. Optimize Code:
    • Remove unnecessary comments, debugging code, and unused files.
    • Minimize and bundle any JavaScript, CSS, or other assets.
  3. Database Configuration:
    • Update database credentials for production. Ensure sensitive information like database passwords is securely handled using environment variables.
    • Configure the database connection for high performance, like setting the right charset and collation.
  4. Security Checks:
    • Ensure input sanitization and validation are properly implemented.
    • Review your codebase for any security flaws like SQL injection vulnerabilities, XSS, or CSRF.

Choosing a Hosting Provider

When deploying a PHP application, one of the first decisions you need to make is choosing the right hosting provider. There are different types of hosting services available:

  1. Shared Hosting:
    • Best for small applications and websites with low traffic.
    • Less control over the server environment but cost-effective.
    • Providers like Bluehost, HostGator, and GoDaddy offer shared hosting with PHP support.
  2. VPS Hosting:
    • Provides more control over the server environment.
    • Suitable for medium to large-scale applications that require more resources and flexibility.
    • Providers like DigitalOcean, Linode, and AWS Lightsail offer VPS hosting.
  3. Dedicated Hosting:
    • Best for large applications with heavy traffic or resource-intensive tasks.
    • You get a dedicated server, but it’s more expensive and requires expertise in server management.
  4. Cloud Hosting:
    • Providers like AWS, Google Cloud, and Microsoft Azure allow you to scale your PHP applications based on demand, offering both flexibility and reliability.

Setting Up a Web Server for PHP

To serve PHP applications, you will need to install a web server that supports PHP. The most common options are Apache and Nginx.

Apache Setup for PHP

  1. Install Apache: sudo apt-get update sudo apt-get install apache2
  2. Install PHP: sudo apt-get install php libapache2-mod-php
  3. Restart Apache: sudo systemctl restart apache2

Nginx Setup for PHP

  1. Install Nginx: sudo apt-get update sudo apt-get install nginx
  2. Install PHP-FPM: sudo apt-get install php-fpm
  3. Configure Nginx: Edit the /etc/nginx/sites-available/default file to ensure that PHP requests are passed to PHP-FPM. location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; }
  4. Restart Nginx: sudo systemctl restart nginx

Deploying on Shared Hosting vs. VPS

When deploying a PHP application, you will need to consider whether you are using shared hosting or a VPS.

Shared Hosting

  1. File Upload: Shared hosting typically provides a cPanel or a file manager to upload your PHP files using FTP/SFTP.
  2. Database: You can create and manage databases through cPanel’s MySQL interface.
  3. PHP Configuration: Shared hosts may not allow full access to PHP configurations, but they provide options to edit certain PHP settings via .htaccess files or cPanel options.

VPS

  1. SSH Access: With a VPS, you have full control over your server. You can upload files using SFTP/SSH and configure your server as needed.
  2. Custom Configuration: You can configure your server settings, optimize PHP, install necessary extensions, and install any required software.

Deploying with FTP/SFTP

One of the simplest ways to deploy a PHP application is through FTP or SFTP. Here’s how you can upload your files using SFTP:

  1. Use an FTP Client: Software like FileZilla or Cyberduck can help you upload your files to the server.
    • Connect to the server using the server’s IP, your FTP username, and password.
    • Navigate to the directory where your PHP application should reside, and upload all your files.
  2. Upload Files: Ensure that all PHP files, images, CSS, and JavaScript are uploaded. Double-check that no important files are left out.
  3. Permissions: Set the correct file permissions for your uploaded files to ensure they are executable and readable.

Setting Up and Configuring a Database

If your PHP application uses a database (such as MySQL), you need to set it up on the server. Most hosting providers offer an easy-to-use interface like phpMyAdmin or cPanel MySQL Database Wizard.

  1. Create a Database: Use phpMyAdmin or MySQL command-line tools to create a new database. CREATE DATABASE your_database_name;
  2. Create Database Tables: Run SQL queries to create the necessary tables in your database.
  3. Update Database Connection: Ensure your PHP application’s database connection settings are updated to match the production server’s credentials.

Ensuring Security Before Deployment

Before deploying, ensure your application is secure:

  • Use HTTPS: Set up an SSL certificate to ensure secure communication between the server and users.
  • Sanitize Inputs: Make sure all user inputs are sanitized and validated to avoid SQL injection and XSS attacks.
  • Disable Unnecessary PHP Functions: Disable functions like exec(), shell_exec(), and others that could pose security risks in a production environment.
  • Use Proper Permissions: Ensure your files and directories have the correct permissions (e.g., 755 for directories, 644 for files).

Continuous Deployment with Git

For continuous deployment, Git is a great tool to keep your application up-to-date. Platforms like GitHub, GitLab, and Bitbucket offer deployment pipelines that automate the process.

  1. Set Up Git on Server: sudo apt-get install git
  2. Clone Your Repository: git clone https://github.com/yourusername/yourrepository.git /var/www/yourapp
  3. Automate Deployment: Use Git hooks or continuous integration (CI) tools to automate deployments whenever you push changes to the repository.

Conclusion

Deploying a PHP application is an essential step in bringing your application to life. By preparing your PHP app for production, selecting the right hosting provider, and securing your environment, you can ensure that your application is accessible, efficient, and secure.

In this module, we’ve covered the steps to deploy a PHP application, from configuring your environment and choosing the hosting provider to uploading files and setting up databases. Continuous deployment with Git further streamlines the process, ensuring that updates are applied smoothly.

Creating an Admin Dashboard in PHP

0
php course
php course

Table of Contents

  • Introduction to Admin Dashboards
  • Key Features of an Admin Dashboard
  • Setting Up the Admin Panel Database Structure
  • Building the Admin Dashboard Layout
  • Implementing Authentication for Admin Panel
  • Displaying Data on the Dashboard
  • Conclusion

Introduction to Admin Dashboards

An admin dashboard is an essential part of any content management system (CMS) or e-commerce platform. It provides administrators with an easy-to-use interface to manage the website’s content, user interactions, and other crucial information. In this module, we will walk you through the process of creating a basic admin dashboard using PHP and MySQL.

The admin dashboard will include an authentication system to ensure that only authorized users can access it. Additionally, we will implement a simple data display section where admins can view product statistics, user activity, and order summaries.


Key Features of an Admin Dashboard

For our basic admin dashboard, we will include the following features:

  1. Login Authentication: Admins must log in to access the dashboard.
  2. User Interface: A simple and intuitive interface for the admin to view and manage key data.
  3. Data Display: The ability to view essential statistics such as the number of products, users, and orders.
  4. Product Management: The ability to add, edit, and delete products.
  5. User Management: The ability to view, edit, and delete user accounts.
  6. Order Management: A section to manage and track customer orders.

Setting Up the Admin Panel Database Structure

Before we begin building the dashboard, we need to have a user authentication system in place. The following SQL code will create two important tables:

  1. Users: To store admin login information.
  2. Products: For managing products in the e-commerce system.
-- Table for storing admin user information
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
role ENUM('admin', 'user') DEFAULT 'admin'
);

-- Table for storing product information
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
price DECIMAL(10, 2) NOT NULL,
stock INT DEFAULT 0
);

In the users table, we store the admin’s username, password, and role. The products table is used to store the details of each product, including its name, description, price, and stock quantity.


Building the Admin Dashboard Layout

The admin dashboard layout will have a sidebar navigation menu to access various sections like Dashboard, Manage Products, Manage Users, and Manage Orders. Here’s a simple example of how we can structure the layout using HTML and CSS.

admin_dashboard.php

<?php
// Include session and authentication check
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
header('Location: admin_login.php');
exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Dashboard</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
}
.sidebar {
width: 250px;
background-color: #333;
color: white;
padding-top: 20px;
position: fixed;
height: 100vh;
}
.sidebar a {
display: block;
color: white;
padding: 15px;
text-decoration: none;
font-size: 18px;
}
.sidebar a:hover {
background-color: #575757;
}
.content {
margin-left: 260px;
padding: 20px;
width: 100%;
}
</style>
</head>
<body>
<div class="sidebar">
<h2>Admin Panel</h2>
<a href="admin_dashboard.php">Dashboard</a>
<a href="manage_products.php">Manage Products</a>
<a href="manage_users.php">Manage Users</a>
<a href="manage_orders.php">Manage Orders</a>
<a href="logout.php">Logout</a>
</div>
<div class="content">
<h1>Welcome to the Admin Dashboard</h1>
<p>Here, you can manage products, users, and orders.</p>

<!-- Display basic data -->
<div>
<h2>Dashboard Overview</h2>
<p>Total Products: <?php echo getProductCount(); ?></p>
<p>Total Users: <?php echo getUserCount(); ?></p>
<p>Total Orders: <?php echo getOrderCount(); ?></p>
</div>
</div>
</body>
</html>

<?php
// Function to get product count
function getProductCount() {
global $pdo;
$stmt = $pdo->query("SELECT COUNT(*) FROM products");
$count = $stmt->fetchColumn();
return $count;
}

// Function to get user count
function getUserCount() {
global $pdo;
$stmt = $pdo->query("SELECT COUNT(*) FROM users");
$count = $stmt->fetchColumn();
return $count;
}

// Function to get order count
function getOrderCount() {
global $pdo;
$stmt = $pdo->query("SELECT COUNT(*) FROM orders");
$count = $stmt->fetchColumn();
return $count;
}
?>

In this layout:

  • The sidebar allows navigation between different sections of the admin panel.
  • The content section contains basic dashboard statistics and will later show data on products, users, and orders.

Implementing Authentication for Admin Panel

To ensure that only authorized users can access the admin dashboard, we need to implement an authentication system.

admin_login.php

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Authenticate user
$username = $_POST['username'];
$password = $_POST['password'];

global $pdo;
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user && password_verify($password, $user['password'])) {
$_SESSION['admin_logged_in'] = true;
$_SESSION['user_id'] = $user['id'];
header('Location: admin_dashboard.php');
exit();
} else {
$error = "Invalid username or password.";
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Login</title>
</head>
<body>
<h1>Admin Login</h1>
<form action="admin_login.php" method="POST">
<label for="username">Username</label>
<input type="text" name="username" required><br>
<label for="password">Password</label>
<input type="password" name="password" required><br>
<button type="submit">Login</button>
</form>

<?php if (isset($error)) { echo "<p>$error</p>"; } ?>
</body>
</html>

This login page checks if the provided username and password match the admin’s credentials stored in the database. If successful, the user is redirected to the dashboard.


Displaying Data on the Dashboard

In the dashboard, we are displaying basic statistics like the total number of products, users, and orders. You can expand this functionality by adding more advanced features, such as listing the latest orders or showing detailed product information.

You can also extend the admin dashboard by adding sections for product management, user management, and order tracking.


Conclusion

In this module, we created a basic admin dashboard with login authentication, a sidebar navigation system, and essential data like product, user, and order statistics. This dashboard serves as a foundation for managing e-commerce features in an admin panel.

You can expand the functionality of this dashboard by adding more complex features such as analytics, order management, user roles, and advanced product filtering options.

Building a Basic E-commerce Cart in PHP

0
php course
php course

Table of Contents

  • Introduction to Building an E-commerce Cart
  • Key Features of the E-commerce Cart
  • Setting Up the Database for E-commerce
  • Creating the Cart Model and Database Operations
  • Building the Cart Pages
  • Adding Products to the Cart
  • Displaying the Cart Contents
  • Handling Cart Updates and Deletions
  • Conclusion

Introduction to Building an E-commerce Cart

Building an e-commerce cart is a fundamental project for learning PHP and web development. It simulates a real-world shopping cart experience where users can add products, view the cart contents, and make changes before proceeding to checkout. In this module, we will build a simple e-commerce cart system using PHP and MySQL, which will be functional enough for testing various e-commerce features.

By the end of this module, you will have a basic e-commerce cart where users can add products, view their cart, and modify their selections.


Key Features of the E-commerce Cart

For this simple e-commerce cart, the following features will be included:

  1. Product Display: A page showing available products that users can add to their cart.
  2. Add Products to Cart: The ability to add products to a shopping cart.
  3. View Cart: A page to view the items currently in the cart.
  4. Update Cart: Users can update quantities or remove items from the cart.
  5. Session-based Cart: The cart will be session-based, so it will persist throughout the user’s visit to the website.

Setting Up the Database for E-commerce

For our basic e-commerce cart system, we will need two tables:

  1. Products: To store product information.
  2. Cart: To store the items added to the shopping cart.

Here is the SQL to create the products and cart tables:

-- Table for storing product information
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
price DECIMAL(10, 2) NOT NULL,
image VARCHAR(255) NOT NULL
);

-- Table for storing cart items (this table is for the session cart, not a permanent database table)
CREATE TABLE cart (
id INT AUTO_INCREMENT PRIMARY KEY,
product_id INT,
quantity INT,
session_id VARCHAR(255),
FOREIGN KEY (product_id) REFERENCES products(id)
);

The products table stores information about each product, including its name, description, price, and image. The cart table stores the items added to the cart, with a reference to the products table and a quantity field. The session_id will ensure that the cart is unique to each user.


Creating the Cart Model and Database Operations

We will create a CartModel class to handle operations related to the shopping cart, such as adding products, retrieving the cart, updating quantities, and removing items.

Database Connection

We’ll use the same db.php file for database connections as in the previous modules.

<?php
// db.php
$host = 'localhost';
$dbname = 'ecommerce_system';
$username = 'root';
$password = '';

try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
?>

Cart Model

Now let’s create the CartModel.php class to handle the cart operations:

<?php
require_once 'db.php';

class CartModel {

// Add a product to the cart
public function addToCart($productId, $quantity) {
session_start();
$sessionId = session_id();

global $pdo;
$sql = "SELECT * FROM cart WHERE product_id = ? AND session_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$productId, $sessionId]);
$cartItem = $stmt->fetch(PDO::FETCH_ASSOC);

if ($cartItem) {
// If product already exists in the cart, update the quantity
$newQuantity = $cartItem['quantity'] + $quantity;
$sql = "UPDATE cart SET quantity = ? WHERE product_id = ? AND session_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$newQuantity, $productId, $sessionId]);
} else {
// Otherwise, insert a new cart item
$sql = "INSERT INTO cart (product_id, quantity, session_id) VALUES (?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$productId, $quantity, $sessionId]);
}
}

// Get all items in the cart
public function getCartItems() {
session_start();
$sessionId = session_id();

global $pdo;
$sql = "SELECT * FROM cart WHERE session_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$sessionId]);
$cartItems = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch product details for each item in the cart
foreach ($cartItems as &$item) {
$sql = "SELECT * FROM products WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$item['product_id']]);
$item['product'] = $stmt->fetch(PDO::FETCH_ASSOC);
}

return $cartItems;
}

// Update quantity of a cart item
public function updateCartItem($productId, $quantity) {
session_start();
$sessionId = session_id();

global $pdo;
$sql = "UPDATE cart SET quantity = ? WHERE product_id = ? AND session_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$quantity, $productId, $sessionId]);
}

// Remove an item from the cart
public function removeCartItem($productId) {
session_start();
$sessionId = session_id();

global $pdo;
$sql = "DELETE FROM cart WHERE product_id = ? AND session_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$productId, $sessionId]);
}

// Clear the entire cart
public function clearCart() {
session_start();
$sessionId = session_id();

global $pdo;
$sql = "DELETE FROM cart WHERE session_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$sessionId]);
}
}
?>

The CartModel class provides several methods:

  • addToCart(): Adds a product to the cart or updates the quantity if the product already exists.
  • getCartItems(): Retrieves all items in the cart, including product details.
  • updateCartItem(): Updates the quantity of a product in the cart.
  • removeCartItem(): Removes a product from the cart.
  • clearCart(): Clears all items in the cart.

Building the Cart Pages

Now that the back-end is set up, let’s create the front-end pages for the cart system.

Product Listing Page (products.php)

This page will display all available products that users can add to the cart:

<?php
require_once 'CartModel.php';

$cartModel = new CartModel();

// Fetch products from the database
global $pdo;
$sql = "SELECT * FROM products";
$stmt = $pdo->query($sql);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Product Listing</title>
</head>
<body>
<h1>Products</h1>
<ul>
<?php foreach ($products as $product): ?>
<li>
<img src="<?php echo $product['image']; ?>" alt="<?php echo $product['name']; ?>">
<h3><?php echo $product['name']; ?></h3>
<p><?php echo $product['description']; ?></p>
<p>Price: $<?php echo $product['price']; ?></p>
<form action="add_to_cart.php" method="POST">
<input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
<label for="quantity">Quantity:</label>
<input type="number" name="quantity" value="1" min="1">
<button type="submit">Add to Cart</button>
</form>
</li>
<?php endforeach; ?>
</ul>
</body>
</html>

This page displays each product’s name, description, price, and an “Add to Cart” button.


Add to Cart (add_to_cart.php)

This page handles adding products to the cart:

<?php
require_once 'CartModel.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$productId = $_POST['product_id'];
$quantity = $_POST['quantity'];

$cartModel = new CartModel();
$cartModel->addToCart($productId, $quantity);

header('Location: cart.php');
exit();
}
?>

This script receives the product ID and quantity from the form and adds the item to the cart using the addToCart() method.


Displaying the Cart (cart.php)

Finally, let’s create a page where users can view their cart:

<?php
require_once 'CartModel.php';

$cartModel = new CartModel();
$cartItems = $cartModel->getCartItems();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Your Cart</title>
</head>
<body>
<h1>Your Shopping Cart</h1>
<ul>
<?php foreach ($cartItems as $item): ?>
<li>
<h3><?php echo $item['product']['name']; ?></h3>
<p>Price: $<?php echo $item['product']['price']; ?></p>
<p>Quantity: <?php echo $item['quantity']; ?></p>
<form action="update_cart.php" method="POST">
<input type="hidden" name="product_id" value="<?php echo $item['product']['id']; ?>">
<input type="number" name="quantity" value="<?php echo $item['quantity']; ?>" min="1">
<button type="submit">Update Quantity</button>
</form>
<a href="remove_cart_item.php?id=<?php echo $item['product']['id']; ?>">Remove</a>
</li>
<?php endforeach; ?>
</ul>
<a href="checkout.php">Proceed to Checkout</a>
</body>
</html>

This page displays the products in the cart along with their quantities and allows the user to update or remove items.


Conclusion

In this module, we built a basic e-commerce cart using PHP and MySQL. We created the necessary database tables and implemented the logic to add, update, and remove items from the cart. The cart is session-based, which ensures that it persists across pages during the user’s visit.

This cart system is a great foundation for a more complex e-commerce website. In future modules, you could expand this system by adding features like user authentication, checkout, payment processing, and order history.