HTML CSS Javascript PHP MySQL To Build A Website (Simple Example)

Welcome to a beginner’s tutorial and simple example of 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!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

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

2A) THE SQL

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

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

ALTER TABLE `products`
  MODIFY `product_id` bigint(20) NOT NULL AUTO_INCREMENT; 
 
-- (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.');

 

2B) 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.

 

 

2C) 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

3A) THE SCRIPT

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

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

 

3B) PHP NOTES & EXPLANATION

PHP is the next piece of the foundation, and the above is an oversimplified 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

4A) 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 -->
    <div id="our-books"><?php 
      require "2-products.php";
      foreach ($products as $p) { ?>
      <div class="bookWrap" data-id="<?=$p["product_id"]?>">
        <img class="bookImg" src="book.png">
        <div class="bookTitle"><?=$p["product_name"]?></div>
        <div class="bookDesc"><?=$p["product_description"]?></div>
      </div>
      <?php }
    ?></div>
  </body>
</html>

 

4B) 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

5A) THE SCRIPT

4-style.css
/* (A) WHOLE PAGE */
* {
  font-family: Arial, Helvetica, sans-serif;
  box-sizing: border-box;
}
body {
  max-width: 600px;
  padding: 10px;
  margin: 0 auto;
  background: #f2f2f2;
}
 
/* (B) BOOKS */
#books {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  grid-gap: 10px;
}
.bookWrap {
  border: 1px solid #dbdbdb;
  background: #fff;
}
.bookImg {
  display: block;
  width: 100%;
}
.bookTitle {
  font-weight: 700;
  font-size: 16px;
  color: #333;
}
.bookDesc {
  padding-top: 0;
  font-size: 14px;
  color: #848484;
}

 

5B) CSS NOTES & EXPLANATION

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

 

 

STEP 6) THE JAVASCRIPT

6A) THE SCRIPT

5-script.js
window.addEventListener("load", () =>{
  // (A) GET ALL BOOKS
  var books = document.querySelectorAll(".bookWrap");
 
  // (B) ATTACH ONCLICK TO ALL BOOKS
  for (let book of books) {
    book.onclick = () => {
      // (B1) GET SELECTED BOOK ID, NAME, DESCRIPTION
      var id = book.dataset.id,
          name = book.querySelector(".bookTitle").innerHTML,
          desc = book.querySelector(".bookDesc").innerHTML;
 
      // (B2) SHOW IN DIALOG BOX
      alert(`You have selected - ID: ${id}, TITLE: ${name} DESC: ${desc}`);
    };
  }
});

 

6B) 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 the cart, checkout, submit forms, form checks, load more content from the server, change themes, etc… Pretty much all kinds of processing that are dynamic.

 

EXTRAS

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, and page design.
  • Development – Actual coding.
  • Testing & Deployment – Test the code, and 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

 

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!

15 thoughts on “HTML CSS Javascript PHP MySQL To Build A Website (Simple Example)”

  1. As soon as I push the submit, instead of showing MySQL results I get a blank page. Using correct host, user, pwd, dbname in new mysqli_connect, and not seeing the echo for connected of for error (just before ‘die’). What’s going on?? It blanks at the connect string. Host gave me the credentials.

  2. Hi – thanks for posting a clear explanation of how each section of code works. I am not sure of what causes the various files to be loaded. I can see that 3-HTML uses a link to 4-style-css and to load 5-script-js. I am not sure what the user accesses to start the process, and what causes forms 1 and 2 to be executed.

    1. Users normally access http://site.com/3-html-page.php. Do a quick trace and it will explain itself.

      * <link href="4-style.css"> Loads the CSS
      * <script src="5-script.js"> Loads the Javascript
      * require "2-products.php"; Loads the PHP which will then fetch products from the database.

Leave a Comment

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