Build an Online Store Today with PayPal, PHP, and MySQL

Build an Online Store Today with PayPal, PHP, and MySQL

nce upon a time building a Web front to a store was an enormous task, involving expensive specialists. However, over time, technologies have developed that allow anybody to build their own store, and handle transaction fulfillment through the well-known, open access payment system of PayPal. In this article, you’ll build a fictional store that stocks and sells sportswear. You’ll need a PHP/MySQL-enabled Web server or site. If you don’t have one, don’t worry?all the details for building your own are in this article. If you don’t know any PHP or MySQL, the same article is also a good place to start.

To build the store, you need a database that contains information about the products that you have for sale and their current stock levels.

To build the table for products, use this SQL code:

CREATE TABLE `products` (  `id` int(11) NOT NULL auto_increment,  `description` varchar(100) NOT NULL default '',  `picurl` varchar(100) NOT NULL default '',  `price` decimal(10,0) NOT NULL default '0',  `stockcount` int(11) NOT NULL default '0',  `weight` int(11) NOT NULL default '0',  `category` int(11) NOT NULL default '0',  `detail` text NOT NULL,  PRIMARY KEY  (`id`)) TYPE=MyISAM AUTO_INCREMENT=1 ; 

This creates a table with the following fields:

  • ID: a unique ID for the product type
  • Description: a textual description of the product
  • PicURL: a URL to a picture of the product
  • Price: the cost of the product
  • Stockcount: the number of items of this product presently in stock
  • Weight: how heavy the product it (in pounds), used to calculate shipping
  • Category: the category of the product (see more on this later)
  • Detail: a detailed description of the product
Figure 1. The Products Table: This is data in the products table using PHPMY ADMIN.

Load this database with some dummy information (a sample is available in the download) as described. You don’t need to set the ID field as it is an auto_increment type.

Next, you’ll need a table of categories for your data. This will make it easier for your customers to browse related data. For example, if your store sells soccer merchandise (as this one does), the category could be team-based. So when customers enter your site, they can browse based on team, or search for a specific item. Assigning a category ID to the team enables this, and a separate table that associates that category ID with some friendly text makes it easier for your shoppers.

The code below shows the SQL used to create the Categories table. Figures 1 and 2 show data in these fields using PHPMYADMIN.

Author’s Note: PHPMYADMIN is an open source PHP tool for managing online databases. If you want to use it, you can check it out in this article, or you can visit its homepage.

CREATE TABLE `categories` ( `id` int(11) NOT NULL auto_increment,  `description` varchar(100) NOT NULL default '',  PRIMARY KEY  (`id`)) TYPE=MyISAM AUTO_INCREMENT=1 ; 

Figure 2. The Categories Table: This is data in the products table using PHPMY ADMIN.
 
Figure 3. The Storefront in Action: A simple PHP page introduces customers to your store and allows them to browse or search.

The next thing you will need is your storefront. This is a simple PHP page introducing people to your store and allowing them to browse or search your products. You can see some of the HTML code for this in the following code, and a screenshot of a sample one in Figure 3.

Browse

This example is very simple and straightforward. It allows your users to access your products from the storefront in one of two ways.

  1. They can browse the products using browse.php. The storefront has hyperlinks that allow you to look at the merchandise for each of the teams with stocked goods. You will notice that even though there are 10 hyperlinks, they all link to the same PHP page! They are differentiated by the URL parameter that they pass to this page (browse.php?teamid=x). When PHP runs the page, it pulls in that parameter and generates the data accordingly. You will see this in more detail later on. What is also nice about this page is that these links and parameters are generated automatically based on the categories information in the database. Therefore, if a new team joins the league and has products, or a team folds or changes its name, you simply edit the database and the Web page will follow. You don’t need to rewrite your page. The following page will show you how it’s done.
  2. Your users can also search your database for the specific item that they want. For a small DB like this one, the advantage isn’t obvious, but if you can imagine a larger store where they stock hundreds of different items for each team?from mugs to baby bibs?you may not want to page through hundreds of these to find that elusive calendar. Instead you would search for ‘Seattle Calendar’ or something like that, and get taken straight to a list of matching items. This functionality is achieved using an HTML form, that POSTs information to a PHP page (search.php) that runs the search against the data and renders the results. This form is shown in the next code block, and the code for the search results page is shown later.

Building the First Page
The first page that you will build is the browse page, browse.php. The easiest way to do this is to use an HTML designer like FrontPage or DreamWeaver to design a template HTML page that has the layout and details of the page. Browse.htm, which can be found in the source code for this article, was designed like this, and can be seen in Figure 4. You can then take this HTML and turn it into a PHP page by changing the file extension to .php, and adding the code to drive this page from a database.

If you look under the hood of this page, you will see that it has four tables.

The first table is at the top of the page with Team 1, Team 2, and Team 3 as columns. For the PHP, you will want to write X number of columns where X is the total number of categories, and the contents of each column will be the text associated with that category. Finally, you will want that text to link back to this page, passing the ID of the category to the page so that the rest of the page will display the products in that category. Take a look at the PHP/HTML mixture that achieves this:

'>

As you can see, the code is quite straightforward. You first output the

in html, and then the (table row). You then kick into PHP and run a query of all categories. Iterating through the results of this query, you then output the
(table column), embedding the contents of each record in turn within this TD. You want to embed two things: first, the ID, so that the URL link will read browse.php?ID=X where X is the ID of the current record. Second is the text within the TD, which you should set to the description of the current record.

The other three tables on the template page are three examples of how the product details would be rendered. The real ones will be generated using an iteration through the products of that category within the database.

The code for this is in Listing 1.

Figure 4. The Basic Layout: the Browse Page: This shows the basic layout for the browse page.

This may look a little difficult to read, but once you understand the HTML that constructed the template table you will see that it is quite straightforward. It simply queries the DB for the full list of products within the specific category, and then, looping through each one outputs a table with the picture, description and price details. It also has some logic to calculate the shipping cost based on the weight, and if the product is currently out of stock, it doesn’t give a link to buy that product. You can see this screen in action in Figure 5. You may notice that the teams I have used in this example are fictitious, so no pictures of their jerseys are available, and the pictures in the sample come from other teams.

Searching
The following SQL shows an example of SQL that searches the DB for products that match the word ‘Green.’

SELECT *FROM `products`WHERE ( ( Upper(`description`) like '%GREEN%') OR  ( Upper(`detail`) like '%GREEN%')) 

Looking back at the home page of the Web site, you will see that the form submits a text field called T1K to the search page. Your search PHP will then take this as a $_POST parameter, and can build the query from it as shown in below:

if(isset($_POST['T1']))      $SearchParam = strtoupper($_POST['T1']);else      $SearchParam = "";  ..

From here, the rest proceeds exactly like the browse screen (Listing 1) to produce identical results (Figure 5).

Buying the Product with PayPal
In Figure 5, you saw 'Buy It Now' links on products that were in stock. Clicking these will take you to a PayPal payment page. You could have populated this screen with the PayPal buttons, and on a live site that would be a good idea to prevent another click. For simplicity of code, this example separates the PayPal button generation onto a separate PHP page called buyit.php.

PayPal uses a Forms submission mechanism to process payments. All you have to do is put a form on your Web site that links to their site to send the payment to you. An example of a PayPal form that sends $75.00 to a PayPal account called '[email protected]':

Figure 5. Product Browsing in Action: This shows how the code in Listing 1 will look.

Therefore, if you write a PHP page that generates this HTML, preloaded for the product ID, your PayPal e-mail address and relevant pricing, you can sell your goods online. If you remember back to the browse/search pages, they gave a hyperlink to buyit.php?id=X where X depends on which product you link. Using this information, you can query the DB for the details of X, and generate the correct button (see Listing 2).

It would be much more efficient and user friendly if this code was part of browse.php and search.php, embedding the PayPal button on the search results instead of having another click. It was separated here for readability only.

A user now clicking on this button will be taken through the workflow of PayPal to send you their hard earned money.

The next steps could be to use the Instant Payment Notification scheme on PayPal to detect that the payment has been received, and as the ID of the product is known, this could call your shipping service to note that the goods need to be shipped to the buyer as well as automatically removing the inventory levels for the purchased products.

This article hopefully gave you a good start into building your own online store, loading it with products and making those products browseable and searchable by your customers as well as offering a methodology whereby they can pay you for those products! Have fun, and happy selling!

devx-admin

devx-admin

Share the Post:
Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of constructing residential and commercial buildings.

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

©2023 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.

Sitemap