Simple Shopping Cart With PHP & MySQL

Simple Shopping Cart With PHP & MySQL
Simple Shopping Cart With PHP & MySQL

आज इस आर्टिकल में हम आपको Simple Shopping Cart With PHP & MySQL के बारे में बताएंगे।

  • Shopping Cart बनाना काफी आसान है, बस आपको पता होना चाहिए आपको करना है।
  • इस आर्टिकल में हम आपको कुछ कोड देंगे जिसकी मदद से आप अपने खुद से Shopping Cart बनाना सीख सकते है।
  • साथ में हम कुछ वीडियोस भी ऐड करेंगे ताकि आपको कोड को लिखने में और समझने में भी आसानी हो जाए ।
  • तो चलिए Simple Shopping Cart With PHP & MySQL कैसे बनाते है सीखते है।
Simple Shopping Cart With PHP & MySQL
Simple Shopping Cart With PHP & MySQL

Simple Shopping Cart With PHP & MySQL

सबसे पहले आपको यह जानना जरुरी है की आपको किन किन चीजों की जरूरत होगी। नीचे हम एक लिस्ट दे रहे है जिसकी मदद से आप जान सकते है की आपको पहले क्या करना है और फिर क्या करना है।

Files

  • config.php
  • index.php
  • styles.css ( you can use CDN link for Bootstrap or offline bootstrap file 4.5.2 version used)

सबसे पहला काम

  • सबसे पहले आपको एक डेटाबेस बनाना है और इसके बाद में उसमें एक टेबल बनानी है।
  • डेटाबेस का नाम हम यहाँ cart रखेंगे और टेबल का नाम products रखेंगे।
  • इसके बाद में आपको इस टेबल में कुछ कॉलम रखने है. जैसे id, name, code, price, image

Config.php

इस फाइल में अपने database से कनेक्शन सेटअप करेंगे जिससे की हम database से डाटा आसानी से fetch कर सके।

index.php

इस फाइल में सारा वो डाटा रखेंगे जिससे हम user को अपना cart दिखा सके और उसके cart में Item add और Remove करवा सके।

styles.css

इस फाइल में हम bootstrap का ऑफलाइन कोड रखेंगे जिससे अगर internet की connectivity ना होने पर भी हम अपने काम को लगातार करते है। CDN लिंक से अगर आपका नेट बंद हो जाता है तो आप के bootstrap class यूज़ कर सकते है।

SQL File

-- --------------------------------------------------------
-- Host:                         localhost
-- Server version:               5.7.24 - MySQL Community Server (GPL)
-- Server OS:                    Win64
-- HeidiSQL Version:             10.2.0.5599
-- --------------------------------------------------------


-- Dumping database structure for cart
CREATE DATABASE IF NOT EXISTS `cart` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `cart`;

-- Dumping structure for table cart.products
CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(191) NOT NULL,
  `code` int(10) unsigned NOT NULL,
  `price` double(10,2) unsigned NOT NULL,
  `image` varchar(191) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

-- Dumping data for table cart.products: ~2 rows (approximately)
/*!40000 ALTER TABLE `products` DISABLE KEYS */;
INSERT INTO `products` (`id`, `name`, `code`, `price`, `image`) VALUES
    (1, 'Acer Nitro Laptop', 121, 89000.00, '/images/image1.jpg'),
    (2, 'Monitor Stand', 122, 5000.00, '/images/image2.jpg');

ये SQL कोड है जिसको अगर आप अपने Query सेक्शन में run करेंगे तो आपका cart और products नाम से टेबल अपने आप बन जायेगी और साथ में टेबल के अन्दर कुछ डमी डाटा भी add हो जाएगा।

इस विडियो की मदद से आप अपने database सेटअप को समझ सकते है।

config.php

इस फाइल में छोटा सा कोड लिखेंगे जिससे हम अपने database से कनेक्शन बना पायेंगे।

<?php
$con = mysqli_connect('localhost', 'root', '', 'cart');

if (mysqli_connect_errno()){
    die("Connection Fail: ". mysqli_connect_error());
}

Index.php

इस फाइल में हमारा सारा वो कोड लिखा जाएगा जिससे की user cart में अपने डाटा को add और remove कर सकता है।

इस फाइल में काफी कोड होगा तो इसको मैं आपको कई अलग अलग हिस्सों में समझाने की कोशिश करूँगा।

तो सबसे पहले हमें जो काम करना है वो है database से हमारा डाटा fetch करके उसको show करवाना। इसके लिए आपको कोड और विडियो दोनों नीचे दी गयी है।

<?php
// यहाँ हम कुछ और कोड भी add करेंगे

require_once 'config.php';

// यहाँ हम कुछ और कोड भी add करेंगे

?>



<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Shopping Cart</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>

<div class="container py-5">


// यहाँ हम कुछ और कोड भी add करेंगे

    <!-- first done this -->
    <div class="row">
        <div class="col-md-12">
            <h1>Products List</h1>
            <div class="d-flex">
                <div class="card-deck">
                    <?php
                    $query = "SELECT * FROM products";
                    $product = mysqli_query($con, $query);
                    if (!empty($product)) {
                        while ($row = mysqli_fetch_array($product)) { ?>
                            <form action="index.php?action=add&pid=<?= $row['id']; ?>" method="post">
                                <div class="card" style="width:18rem">
                                    <img class="card-img-top"
                                         src="<?= $row['image']; ?>"
                                         alt="<?= $row['name']; ?>"
                                         width="150">
                                    <div class="card-header d-flex justify-content-between">
                                        <span><?= $row['name']; ?></span>
                                        <span>₹<?= number_format($row['price'], 2); ?></span>
                                    </div>
                                    <div class="card-body d-flex justify-content-between">
                                        <input type="text" name="quantity" value="1" size="2">
                                        <input type="submit" value="Add to Cart" class="btn btn-success btn-sm">
                                    </div>
                                </div>
                            </form>
                        <?php }
                    } else {
                        echo "no products available";
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
</div>

</body>
</html>

इसके बाद में हमें एक cart डिजाईन करना होगा जिसके लिए आपको सिर्फ ये नीचे दी गयी विडियो देखनी है।इस विडियो में हमने सिर्फ आपको dummy cart कैसे डिजाईन करना है उसके बारे में बताया है।

next विडियो में हम जानेगे की कैसे हम अपने cart के dummy डाटा को replace करके वहां अपने डाटा को add कर सकते है। इस विडियो में आपको कुछ प्रॉब्लम का सलूशन भी मिलेगा तो साथ में विडियो जरुर चेक करें।

इसका कोड हम आपको नीचे दे रहे है जो की सिर्फ cart में डाटा add करने के लिए होगा।

<?php
session_start();
require_once 'config.php';

// add, remove, empty
if (!empty($_GET['action'])) {
    switch ($_GET['action']) {
        // add product to cart
        case 'add':
            if (!empty($_POST['quantity'])) {
                $pid = $_GET['pid'];
                $query = "SELECT * FROM products WHERE id=" . $pid;
                $result = mysqli_query($con, $query);
                while ($product = mysqli_fetch_array($result)) {
                    $itemArray = [
                        $product['code'] => [
                            'name' => $product['name'],
                            'code' => $product['code'],
                            'quantity' => $_POST['quantity'],
                            'price' => $product['price'],
                            'image' => $product['image']
                        ]
                    ];
                    if (isset($_SESSION['cart_item']) &&!empty($_SESSION['cart_item'])) {
                        if (in_array($product['code'], array_keys($_SESSION['cart_item']))) {
                            foreach ($_SESSION['cart_item'] as $key => $value) {
                                if ($product['code'] == $key) {
                                    if (empty($_SESSION['cart_item'][$key]["quantity"])) {
                                        $_SESSION['cart_item'][$key]['quantity'] = 0;
                                    }
                                    $_SESSION['cart_item'][$key]['quantity'] += $_POST['quantity'];
                                }
                            }
                        } else {
                            $_SESSION['cart_item'] += $itemArray;
                        }
                    } else {
                        $_SESSION['cart_item'] = $itemArray;
                    }
                }
            }
            break;
//यहाँ हम remove और empty cart के लिए कोड लिखेंगे

    }
}


?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Shopping Cart</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>

<div class="container py-5">
    <div class="d-flex justify-content-between mb-2">
        <h3>Cart</h3>
        <a class="btn btn-danger" href="index.php?action=empty">All Item Remove</a>
    </div>
    <div class="row">
        <?php
            $total_quantity = 0;
            $total_price = 0;
        ?>
        <table class="table">
            <tbody>
            <tr>
                <th class="text-left">Name</th>
                <th class="text-left">Code</th>
                <th class="text-right">Quantity</th>
                <th class="text-right">Item Price</th>
                <th class="text-right">Price</th>
                <th class="text-center">Remove</th>
            </tr>
            <?php
            if (isset($_SESSION['cart_item']) && !empty($_SESSION['cart_item'])){
                foreach ($_SESSION['cart_item'] as $item) {
                    $item_price = $item['quantity'] * $item['price'];
                    ?>
                    <tr>
                        <td class="text-left">
                            <img src="<?= $item['image'] ?>" alt="<?= $item['name'] ?>" class="img-fluid" width="100">
                            <?= $item['name'] ?>
                        </td>
                        <td class="text-left"><?= $item['code'] ?></td>
                        <td class="text-right"><?= $item['quantity'] ?></td>
                        <td class="text-right">₹<?= number_format($item['price'], 2) ?></td>
                        <td class="text-right">₹<?= number_format($item_price, 2) ?></td>
                        <td class="text-center">
                            <a href="index.php?action=remove&code=<?= $item['code']; ?>" class="btn btn-danger">X</a>
                        </td>
                    </tr>

                    <?php
                    $total_quantity += $item["quantity"];
                    $total_price += ($item["price"]*$item["quantity"]);
                }
            }

            if (isset($_SESSION['cart_item']) && !empty($_SESSION['cart_item'])){
                ?>
                <tr>
                    <td colspan="2" align="right">Total:</td>
                    <td align="right"><strong><?= $total_quantity ?></strong></td>
                    <td></td>
                    <td align="right"><strong>₹<?= number_format($total_price, 2); ?></strong></td>
                    <td></td>
                </tr>

            <?php }

                ?>
            </tbody>
        </table>
    </div>


    <!-- first done this -->
    <div class="row">
        <div class="col-md-12">
            <h1>Products List</h1>
            <div class="d-flex">
                <div class="card-deck">
                    <?php
                    $query = "SELECT * FROM products";
                    $product = mysqli_query($con, $query);
                    if (!empty($product)) {
                        while ($row = mysqli_fetch_array($product)) { ?>
                            <form action="index.php?action=add&pid=<?= $row['id']; ?>" method="post">
                                <div class="card" style="width:18rem">
                                    <img class="card-img-top"
                                         src="<?= $row['image']; ?>"
                                         alt="<?= $row['name']; ?>"
                                         width="150">
                                    <div class="card-header d-flex justify-content-between">
                                        <span><?= $row['name']; ?></span>
                                        <span>₹<?= number_format($row['price'], 2); ?></span>
                                    </div>
                                    <div class="card-body d-flex justify-content-between">
                                        <input type="text" name="quantity" value="1" size="2">
                                        <input type="submit" value="Add to Cart" class="btn btn-success btn-sm">
                                    </div>
                                </div>
                            </form>
                        <?php }
                    } else {
                        echo "no products available";
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
</div>

</body>
</html>

हमने यहाँ add वाली functionality add कर ली है, अब हम remove और empty cart का सिस्टम भी add कर लेंगे
जिससे हमारा पूरा कोड कम्पलीट हो जाएगा।

<?php
session_start();
require_once 'config.php';

// add, remove, empty
if (!empty($_GET['action'])) {
    switch ($_GET['action']) {
        // add product to cart
        case 'add':
            if (!empty($_POST['quantity'])) {
                $pid = $_GET['pid'];
                $query = "SELECT * FROM products WHERE id=" . $pid;
                $result = mysqli_query($con, $query);
                while ($product = mysqli_fetch_array($result)) {
                    $itemArray = [
                        $product['code'] => [
                            'name' => $product['name'],
                            'code' => $product['code'],
                            'quantity' => $_POST['quantity'],
                            'price' => $product['price'],
                            'image' => $product['image']
                        ]
                    ];
                    if (isset($_SESSION['cart_item']) &&!empty($_SESSION['cart_item'])) {
                        if (in_array($product['code'], array_keys($_SESSION['cart_item']))) {
                            foreach ($_SESSION['cart_item'] as $key => $value) {
                                if ($product['code'] == $key) {
                                    if (empty($_SESSION['cart_item'][$key]["quantity"])) {
                                        $_SESSION['cart_item'][$key]['quantity'] = 0;
                                    }
                                    $_SESSION['cart_item'][$key]['quantity'] += $_POST['quantity'];
                                }
                            }
                        } else {
                            $_SESSION['cart_item'] += $itemArray;
                        }
                    } else {
                        $_SESSION['cart_item'] = $itemArray;
                    }
                }
            }
            break;
        case 'remove':
            if (!empty($_SESSION['cart_item'])) {
                foreach ($_SESSION['cart_item'] as $key => $value) {
                    if ($_GET['code'] == $key) {
                        unset($_SESSION['cart_item'][$key]);
                    }
                    if (empty($_SESSION['cart_item'])) {
                        unset($_SESSION['cart_item']);
                    }
                }
            }
            break;
        case 'empty':
            unset($_SESSION['cart_item']);
            break;
    }
}


?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Shopping Cart</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>

<div class="container py-5">
    <div class="d-flex justify-content-between mb-2">
        <h3>Cart</h3>
        <a class="btn btn-danger" href="index.php?action=empty">All Item Remove</a>
    </div>
    <div class="row">
        <?php
            $total_quantity = 0;
            $total_price = 0;
        ?>
        <table class="table">
            <tbody>
            <tr>
                <th class="text-left">Name</th>
                <th class="text-left">Code</th>
                <th class="text-right">Quantity</th>
                <th class="text-right">Item Price</th>
                <th class="text-right">Price</th>
                <th class="text-center">Remove</th>
            </tr>
            <?php
            if (isset($_SESSION['cart_item']) && !empty($_SESSION['cart_item'])){
                foreach ($_SESSION['cart_item'] as $item) {
                    $item_price = $item['quantity'] * $item['price'];
                    ?>
                    <tr>
                        <td class="text-left">
                            <img src="<?= $item['image'] ?>" alt="<?= $item['name'] ?>" class="img-fluid" width="100">
                            <?= $item['name'] ?>
                        </td>
                        <td class="text-left"><?= $item['code'] ?></td>
                        <td class="text-right"><?= $item['quantity'] ?></td>
                        <td class="text-right">₹<?= number_format($item['price'], 2) ?></td>
                        <td class="text-right">₹<?= number_format($item_price, 2) ?></td>
                        <td class="text-center">
                            <a href="index.php?action=remove&code=<?= $item['code']; ?>" class="btn btn-danger">X</a>
                        </td>
                    </tr>

                    <?php
                    $total_quantity += $item["quantity"];
                    $total_price += ($item["price"]*$item["quantity"]);
                }
            }

            if (isset($_SESSION['cart_item']) && !empty($_SESSION['cart_item'])){
                ?>
                <tr>
                    <td colspan="2" align="right">Total:</td>
                    <td align="right"><strong><?= $total_quantity ?></strong></td>
                    <td></td>
                    <td align="right"><strong>₹<?= number_format($total_price, 2); ?></strong></td>
                    <td></td>
                </tr>

            <?php }

                ?>
            </tbody>
        </table>
    </div>


    <!-- first done this -->
    <div class="row">
        <div class="col-md-12">
            <h1>Products List</h1>
            <div class="d-flex">
                <div class="card-deck">
                    <?php
                    $query = "SELECT * FROM products";
                    $product = mysqli_query($con, $query);
                    if (!empty($product)) {
                        while ($row = mysqli_fetch_array($product)) { ?>
                            <form action="index.php?action=add&pid=<?= $row['id']; ?>" method="post">
                                <div class="card" style="width:18rem">
                                    <img class="card-img-top"
                                         src="<?= $row['image']; ?>"
                                         alt="<?= $row['name']; ?>"
                                         width="150">
                                    <div class="card-header d-flex justify-content-between">
                                        <span><?= $row['name']; ?></span>
                                        <span>₹<?= number_format($row['price'], 2); ?></span>
                                    </div>
                                    <div class="card-body d-flex justify-content-between">
                                        <input type="text" name="quantity" value="1" size="2">
                                        <input type="submit" value="Add to Cart" class="btn btn-success btn-sm">
                                    </div>
                                </div>
                            </form>
                        <?php }
                    } else {
                        echo "no products available";
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
</div>

</body>
</html>

इस तरह से हम अपना shopping cart कम्पलीट कर सकते है।

प्रोडक्ट की इमेजेज और styles.css की फाइल आप हमारे github अकाउंट से भी चेक कर सकते है जिसका लिंक हम आपको यहाँ दे रहे है।

Source Code – https://github.com/thetestcoder/shoping-cart-exmple-php-mysql

Final Word

  • इस तरह से हम simple shopping cart डिजाईन कर सकते है वो भी सिर्फ PHP और MySQL के साथ।
  • तो अगर आपको इससे जुडी कोई अन्य जानकारी चाहिए।
  • तो आप कमेंट बॉक्स में कमेंट करके पूछ सकते है।

इसे भी पढ़े – जिमीकन्द से रोगों का इलाज – Yam in Hindi

1 Comment

  1. manoj chauhan

    thanks for information. your video is really helpful. I watch many video in Youtube add-to-cart with session But some point i can’t understand. But your video is really helpful.
    thanks for information

Leave a Reply

Your email address will not be published. Required fields are marked *