HTML CSS Javascript PHP MySQL To Build A Website – Simple Example

Welcome to a beginner’s tutorial and simple example on how to use HTML, CSS, Javascript, PHP, and MySQL together to build a website. Just started with web development, and wondering how we can “put” all the different technologies together?

Various technologies and languages work together to create a website, each of them handling a different aspect.

  • HTML deals with the structure and layout of web pages.
  • CSS to handle the visuals and cosmetics.
  • Javascript to add dynamic elements to the webpage.
  • MySQL database to store data permanently.
  • PHP to do server-side processing and transactions.

Yep, some of you guys may already know that. So let us walk through the development of a simple product page in this guide – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes Development Cycle Useful Bits
Work Together

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Create a dummy database and import 1-products.sql.
  • Change the database settings (A) in 2-products.php to your own.
  • Launch 3-html-page.php in your web browser for the demo.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

EXAMPLE DEVELOPMENT CYCLE

All right, let us now get started with the development of the products page itself.

 

STEP 1) THE PLAN – DIVIDE AND CONQUER

It is common for beginners to get paralyzed by “too many things to deal with” and “don’t know where to start”. So the first step in every project is to break things down and lay out a step-by-step plan. In this example of creating a simple product page:

  • Goal & Overview: As Captain Obvious as this may be, we need to create a page to display products from the database.
  • Server-Side Database (MySQL): To keep things simple, the database will only capture the product name and description.
  • Server-Side PHP: Create a script that gets product information from the database.
  • Client-Side HTML & CSS: Use the PHP script to create an HTML page to show the products, CSS for the styling.
  • Client-Side Javascript: Finally, use Javascript to add dynamic elements to the HTML page. For example, what happens when the user clicks on a product.

 

STEP 2) CREATING MYSQL DATABASE TABLES

THE SQL

1-products.sql
-- (A) PRODUCTS TABLE
CREATE TABLE `products` (
  `product_id` int(11) NOT NULL,
  `product_name` varchar(128) NOT NULL,
  `product_description` text
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `products`
  ADD PRIMARY KEY (`product_id`),
  ADD KEY `product_name` (`product_name`);

ALTER TABLE `products`
  MODIFY `product_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; 
 
-- (B) DUMMY PRODUCTS
INSERT INTO `products` (`product_id`, `product_name`, `product_description`) VALUES
  (1, 'Vulture Of Fortune', 'A sweated bump consents across the here separator.'),
  (2, 'Guardian Without Duty', 'Does a table migrate inside an excessive paranoid?'),
  (3, 'Enemies Without Hope', 'A cured parameter fears behind the phenomenon.'),
  (4, 'Lords Of The Void', 'The diary scores around the generalized lie.'),
  (5, 'Doctors And Aliens', 'The diary scores around the generalized lie.'),
  (6, 'Blacksmiths And Criminals', 'A considerable snail works into a purchase.');

 

TABLE STRUCTURE

Field Description
product_id Product ID. The primary key, auto-increment.
product_name The product name. Indexed for search performance.
product_description The product description.

 

 

MYSQL DATABASE NOTES & EXPLANATION

Personally, I will always start with the database, simply because it serves as the foundation of almost every project. It is also important to get the required fields correct right from the start, or changing the database structure later can be a very painful process.

 

STEP 3) SERVER-SIDE PHP SCRIPTS

THE SCRIPT

2-products.php
<?php
// (A) DATABASE SETTINGS - CHANGE TO YOUR OWN !
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8");
define("DB_USER", "root");
define("DB_PASSWORD", "");
 
// (B) CONNECT TO DATABASE
try {
  $pdo = new PDO(
    "mysql:host=" . DB_HOST . ";charset=" . DB_CHARSET . ";dbname=" . DB_NAME,
    DB_USER, DB_PASSWORD, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_NAMED
    ]
  );
} catch (Exception $ex) { exit($ex->getMessage()); }

// (C) GET PRODUCTS
$stmt = $pdo->prepare("SELECT * FROM `products`");
$stmt->execute();
$products = $stmt->fetchAll();

 

PHP NOTES & EXPLANATION

PHP is the next piece of the foundation, and the above is an over-simplified example of how we can use PHP to fetch data from the database… But this is actually kind of bad. In actual projects, we would have created a proper class library, object-oriented style. For example:

class Products {
  function get ($id) {
    // SELECT * FROM `products` WHERE `id`= $ID
  }
 
  function add ($name, $desc) {
    // INSERT INTO `products` (... FIELDS ...)
  }
 
  function delete ($id) {
    // DELETE FROM `products` WHERE `id` = $ID
  }
}

 

STEP 4) HTML PAGE

THE SCRIPT

3-html-page.php
<!DOCTYPE html>
<html>
  <head>
    <title>Products Demo Page</title>
 
    <!-- (A) CSS & JS -->
    <link href="4-style.css" rel="stylesheet">
    <script src="5-script.js"></script>
  </head>
  <body>
    <!-- (B) BOOKS LIST -->
    <h1>OUR BOOKS</h1>
    <div id="our-books"><?php 
      require "2-products.php";
      foreach ($products as $p) { ?>
      <div class="book-wrap" data-id="<?=$p["product_id"]?>">
        <div class="book-title"><?=$p["product_name"]?></div>
        <div class="book-desc"><?=$p["product_description"]?></div>
      </div>
      <?php }
    ?></div>
  </body>
</html>

 

HTML NOTES & EXPLANATION

So what is happening here!? Why is the file extension PHP instead of HTML? That’s right – We are using PHP alongside HTML here. No need to be confused. Remember the script we wrote earlier to fetch product data from the database? We are simply using it on this page to generate the product’s HTML, that’s all.

 

 

STEP 5) THE CSS

THE SCRIPT

4-style.css
/* (A) WHOLE PAGE */
html, body {
  font-family: arial, sans-serif;
}
 
/* (B) BOOKS */
#our-books {
  max-width: 1200px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: auto auto;
  grid-gap: 10px;
}
#our-books .book-wrap {
  background: #f1f1f1;
  padding: 15px;
  border: 1px solid #808080;
}
#our-books .book-wrap:hover {
  cursor: pointer;
  background: #fdffe6;
}
#our-books .book-title {
  font-weight: bold;
  font-size: 1.2em;
  color: #333;
}
#our-books .book-desc {
  margin-top: 10px;
  color: #848484;
}

 

CSS NOTES & EXPLANATION

Nothing much here actually. CSS is the part that deals with cosmetics and styles in HTML.

 

 

STEP 6) THE JAVASCRIPT

THE SCRIPT

5-script.js
window.addEventListener("load", function () {
  // (A) GET ALL BOOKS
  var books = document.getElementsByClassName("book-wrap");
 
  // (B) LOOP THROUGH ALL BOOKS
  for (let book of books) {
    // (B1) ON CLICKING A BOOK
    book.addEventListener("click", function () {
      // (B2) GET SELECTED BOOK ID, NAME, DESCRIPTION
      var id = this.dataset.id,
          name = this.getElementsByClassName("book-title")[0].innerHTML,
          desc = this.getElementsByClassName("book-desc")[0].innerHTML;
 
      // (B3) SHOW IN DIALOG BOX
      alert(`You have selected - ID: ${id}, TITLE: ${name} DESC: ${desc}`);
    });
  }
});

 

JAVASCRIPT NOTES & EXPLANATION

This is yet another overly simplified example. On a “normal” products page, Javascript would have been used to send an “add to cart” process to the server when a product is selected. Also, you can pretty much already guess what Javascript can do – Remove from cart, checkout, submit forms, form checks, load more content from the server, change themes, etc… Pretty much all kinds of processing that are dynamic.

 

THE RESULT

Finally, this is not the prettiest looking award-winning website on the planet. But it should do well enough to demonstrate how we can use all the PHP, MySQL, HTML, CSS, and Javascript together.

 

USEFUL BITS & LINKS

That’s it for all the code, and here are a few small extras that may be useful.

 

SOFTWARE DEVELOPMENT LIFE CYCLE (SDLC)

Congratulations, what you have gone through in the last 15 minutes is called a “software development life cycle” (SDLC).

  • Requirement Analysis – What is required? What does the client need?
  • Planning – Divide-and-conquer. What needs to be done?
  • Design – The database structure, software architecture, page design.
  • Development – Actual coding.
  • Testing & Deployment – Test the code, put it live on the Internet.

Some people may have different steps for the SDLC, but that is the general process. Also, take note that SDLC does not stop after just one cycle – We may review our projects later, and decide that things need to change. The whole SDLC cycle starts again, and it never really ends.

 

 

FRONT-END, BACK-END, FULL-STACK

As a beginner, you need not worry too much actually. In real-world massive projects, there are usually many developers working on the same project, each handling a different component:

  • Project Manager (Full-Stack) – The boss. He/she/it deals with the wide overview, processes, structure of the entire system, and even support for other platforms such as mobile apps.
  • Lead/Senior Web Developers (Full-Stack) – Does everything. HTML, CSS, Javascript, PHP, MySQL, and whatever else. AKA Superman.
  • Junior Web Developers (Front End) – Creates the webpages. HTML, CSS, Javascript.
  • Junior Web Developers (Back End) – Does PHP, MySQL. More on the administration panel and server-side libraries instead.

So yeah, it is only further up the ladder that we need to really deal with “everything and beyond”.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

How HTML, CSS, PHP, Javascript, MySQL Work Together (Click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand – HTML, CSS, Javascript, PHP, MySQL, they are all different components, but they all work together to create a single website or system.

It may be overwhelming at first to deal with many things at once, so take it step-by-step, and the rest will be just like learning how to cycle. Once you catch the gist and flow, it will be much easier. If you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

6 thoughts on “HTML CSS Javascript PHP MySQL To Build A Website – Simple Example”

  1. Fatal error: Uncaught PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘test.products’ doesn’t exist in C:\xampp\htdocs\tamy\2-products.php:22 Stack trace: #0 C:\xampp\htdocs\tamy\2-products.php(22): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\tamy\2-products.php on line 22

  2. I like very much the way you use for explaining this theme, I hope, I can find in the future more articles and documentations of yours.

    Thank you very much.

  3. This helped me get started with my first introduction to PHP. Thank you. Ps. I had to enable my pdo_mysql extension in PHP.ini (might be interested for others) otherwise i only got an “could not find driver” notification.

  4. Looks like an great opportunity to learn and understand how all these languages are integrated to make web site.

    Thank you.

    Manny

Leave a Comment

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