Welcome to our comprehensive PHP tutorial where we'll build a shopping cart from scratch! By the end of this guide, you'll have a solid understanding of PHP and how to implement it in a real-world project. Let's get started! π―
Before we dive in, ensure you have a local development environment set up. We recommend using XAMPP or MAMP.
In PHP, variables are used to store data. Here are some basic data types you'll encounter:
string: A sequence of characters, such as "Hello, World!".integer: Whole numbers, like 123 or -100.float: Decimal numbers, represented as 12.34 or 0.0001.boolean: True or false values, like true or false.array: A collection of values, such as $colors = ["red", "blue", "green"].Our shopping cart will have a simple HTML layout to display products, add to cart, and view cart. Here's a basic structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Shopping Cart</title>
</head>
<body>
<!-- Add your PHP code within the body tags -->
</body>
</html>To use PHP in our HTML file, we'll use the <?php and ?> tags. PHP code within these tags will be executed by the server before the HTML is displayed to the user.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Shopping Cart</title>
</head>
<body>
<?php
// Your PHP code goes here
?>
</body>
</html>Let's start by creating an array with some sample products:
<?php
$products = [
[
"name" => "Product 1",
"price" => 10.99,
"quantity" => 5
],
[
"name" => "Product 2",
"price" => 15.99,
"quantity" => 3
]
];
?>Now, let's display the products using a loop:
<?php
foreach ($products as $product) {
echo "<h2>{$product["name"]}</h2>";
echo "<p>Price: {$product["price"]}</p>";
echo "<p>Quantity: {$product["quantity"]}</p>";
}
?>To add products to the cart, we'll create an empty $_SESSION variable:
<?php
session_start();
if (!isset($_SESSION["cart"])) {
$_SESSION["cart"] = [];
}
?>Now, let's create a function to add products to the cart:
function addToCart($productId) {
global $_SESSION;
if (!isset($_SESSION["cart"][$productId])) {
$_SESSION["cart"][$productId] = 1;
} else {
$_SESSION["cart"][$productId]++;
}
}To display the cart, we'll create a function to get the cart data:
function getCartData() {
global $_SESSION;
return $_SESSION["cart"];
}Now, let's display the cart data:
<?php
$cart = getCartData();
if (!empty($cart)) {
echo "<h2>Cart</h2>";
foreach ($cart as $productId => $quantity) {
echo "<p>Product ID: {$productId}</p>";
echo "<p>Quantity: {$quantity}</p>";
}
}
?>What is the purpose of the `session_start()` function in PHP?
That's it for today! In the next lesson, we'll add more features to our shopping cart, like calculating the total cost and handling product removal. π Stay tuned!