Simple shopping list using php mysql jquery bootstrap

by  
Share:
Simple shopping list using php mysql jquery bootstrap

How many of you have the habit of forgetting things when you go out for shopping? I am definitely one of those guys. Writing down the shopping list item on paper is one of the traditional ways to remember stuff. It was one fine day when I thought why not create a web app to do the same thing. So I created this simple shopping list using PHP Mysql jquery and bootstrap.

View Demo

About shopping list application

Before getting started, let me tell you about the features of this application. This simple shopping list application was created by me with an intent to track down the list of item (digitally) to be purchased when a person goes out for shopping. Have a look at the detailed features below:

  • User can create as many item as they want.
  • User can check the item if they have purchased it.(Ajax feature).
  • Left over item which is not bought/ not available will be left unchecked.
  • User can clear the the entire list in one go, or they can delete a single item individually.
  • Application is created using PHP and MySql and have the usage of PHP PDO classes.
  • Bootstrap Framework has been used for for developing the User Interface ( UI) and also to get mobile friendly look.
  • JavaScript and JQuery has been used for client side validation and triggering/binding events.

Ups and Downs of Shopping List Application

Since nothing is perfect in this world, this application has its ups and downs. Let’s have a look at them

Pro

  • Runs on server, so can be accessed by any devices.
  • Mobile responsive application
  • Multiple user can use this application at the same time.
  • Unlimited number of items can be added to the list

Cons

  • As it runs on server so an internet connection is required.
  • If a person is buying a handful list of items, this app is just an added extra.

Coding the application

Let’s get into the programmer mode. First thing we need to create a database and table for the application. Have a look at the SQL below.

create database shopping;
use shopping;

CREATE TABLE IF NOT EXISTS `tbl_items_list` (
  `itl_id` int(11) NOT NULL AUTO_INCREMENT,
  `itl_items` varchar(255) NOT NULL,
  `itl_status` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`itl_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Once the database is created we can move on and create a configuration file where site constants and database connection code are written. I call this page config.php
<?php
// turn on/off error reporting
error_reporting( E_ALL & ~E_DEPRECATED & ~E_NOTICE );

// site url
define('SITE_URL', 'http://localhost/shopping/');

// database related constants
define('DB_DRIVER', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', 'root');
define('DB_SERVER_PASSWORD', '');
define('DB_DATABASE', 'shopping');

// connecting to database
$dboptions = array(
              PDO::ATTR_PERSISTENT => FALSE, 
              PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, 
              PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
              PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
            );
try {
  $DB = new PDO(DB_DRIVER.':host='.DB_SERVER.';dbname='.DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD , $dboptions);  
} catch (Exception $ex) {
  echo $ex->getMessage();
  die;
}
?>

I am not going to teach about bootstrap framework in this tutorial. You can learn from their official website.

On the home page (index.php) of the application we will display the list of item on the shopping list. Also, we need to give option for adding new items and delete each item or delete the entire list as well. Have a look at the code for listing the shopping list item as a html table.

<?php
// fetching the records from the table
try {
    $sql = "SELECT `itl_id`,`itl_items`,`itl_status` FROM tbl_items_list WHERE 1 ORDER BY itl_id ASC ";
    $stmt = $DB->prepare($sql);
    $stmt->execute();
    $results = $stmt->fetchAll();
} catch (Exception $ex) {
    echo $ex->getMessage();
}
?>

Displaying the records as a html table with check box to check/uncheck the status and a delete option as well.
<?php if (count($results) > 0) { ?>
<table class="table table-striped table-hover table-bordered ">
<thead>
  <tr>
    <th style="width: 10%;"></th>
    <th style="text-align: left;width: 80%;">Item</th>
    <th style="width: 10%;"></th>
  </tr>
</thead>
<tbody>
<?php 
foreach ($results as $res) {
  $item_status = intval($res["itl_status"]);
?>
<tr>
  <td style="text-align: center;vertical-align: middle;">
    <input type="checkbox" name="item[]" value="<?php echo intval($res["itl_id"]); ?>" <?php echo ($item_status == 1) ? 'checked' : ''; ?> class="chk" >
  </td>
  <td style="text-align: left;vertical-align: middle;"><?php echo trim($res["itl_items"]); ?></td>
  <td style="vertical-align: middle;text-align: center;">
   <a style="color: #f00;" href="process_form.php?mode=delete&id=<?php echo intval($res["itl_id"]); ?>" onclick="return confirm('Are you sure you want to delete [<?php echo addslashes(trim($res["itl_items"])); ?>] ?')"><span class="glyphicon glyphicon-remove-circle" style="font-size:18px;"></span> </a> 
  </td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } else { ?>
<div class="well well-lg">No items in the list.</div>
<?php } ?>

When user click on the button ( Add new ), it is redirected to a page add-item.php where user add a new item on the text box and clicks on submit button. Upon both client and server side validation the item is added in the database. (Full code can be found in the download file below)
<!-- html form starts -->
<form class="form-horizontal" name="form1" id="form1" method="post" action="process_form.php">
  <input type="hidden" name="mode" value="add" >
  <input type="text" value="" placeholder="Item" id="item_name" class="form-control" name="item_name">
  <button class="btn btn-primary" type="submit"><i class="glyphicon glyphicon-save"></i> Submit</button>
</form>
<!-- html form ends -->

<?php
// php code for database insert
if ($_POST["mode"] == "add") {
    $item_name = trim($_POST['item_name']);
    if ($item_name == "") {
        $_SESSION["errorType"] = "danger";
        $_SESSION["errorMsg"] = "Please provide item name.";
    } else if (strlen($item_name) < 2) {
        $_SESSION["errorType"] = "danger";
        $_SESSION["errorMsg"] = "Item name must have atleast 2 characters.";
    } else {
        try {
            $sql = "INSERT INTO `tbl_items_list` (`itl_items`, `itl_status`) VALUES (:v, :s)";
            $stmt = $DB->prepare($sql);
            $stmt->bindValue(":v", $item_name);
            $stmt->bindValue(":s", 0);
            $stmt->execute();
            $retval = $DB->lastInsertId();

            if ($retval > 0) {
                $_SESSION["errorType"] = "success";
                $_SESSION["errorMsg"] = "Item added successfully.";
            } else {
                $_SESSION["errorType"] = "danger";
                $_SESSION["errorMsg"] = "Failed to add item.";
            }
        } catch (Exception $ex) {
            $_SESSION["errorType"] = "danger";
            $_SESSION["errorMsg"] = $ex->getMessage();
        }
    }

    header("location:add-item.php");
    exit;
}
?>

There are more codes, which you can see when you download the files available at the end of this post.
  • Delete items
  • Update status of item via Ajax
  • Clear shopping List

Future updates

If I get enough time, I might add some more updates to the current version

  • Multiple user with permission can access the application. ( say like only family members or only friends) .
  • Can track down prices of each item, so user can tally the shopping total.
  • User can add comments for any item ( if any)

I will be glad if you give your suggestion of future updates.

View Demo Download

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Kowsiha v on

Hy buddy how to view tiz project in mobile? I can’t able c tiz project in mi mbl? So plz tel me?

Reply
Shahrukh Khan on

I think you have some network issues. It should be working well.

Reply
rohit singh on

on which platform should i run this code??.plz help

Reply
Shahrukh Khan on

PHP mysql Apache. Try LAMPP/XAMPP

Reply
Karen on

Great work. Have you done this with logged in user?

Reply
Shahrukh Khan on

i don’t understand your question?

Reply
Developer on

Your should update to a version in wich user can save lists and delete/update them if needed, a good feature would be sharing lists through apps such as whatsapp, mail, or to be able to import/export list to the webapp itself.

Very inspiring project, simple but necessary

Reply
Shahrukh Khan on

Thanks for your feedback.
surely that a good point. I will try to do that in my free time.

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.