Go back

Build Your First Website From Scratch With PHP 8 Programming

Read in 4 minutes
Published on: 05 Feb 2021

So you have decided to be a PHP developer and hopefully, you have our article about it. If not, please see some details about becoming a PHP developer and some great resources for learning PHP. Either way, you have some background knowledge about what you are going to do next, and let us proceed towards creating our first PHP website page.  Here you will find a step by step procedure for setting up your development environment and creating our page in PHP 8. Why PHP8? Let us see what it offers:

PHP-8 offers many new features over PHP-7. There are some of them given as following:

1- Union types

Union types are a set of two or more types that suggest that it is possible to use either one of these. 
public function SomeFunction(A|B $input): int|float;
Void can never be part of a union type because it indicates "no return value". nullable unions can be written either by using |null, or by the existing? notation:
public function SomeFunction (A|null $ input): void;

public function SomeFunction (?B $ input): void;    

2- Null-safe operator

With null-safe operator, we can now write our methods with null coalescing-like behaviour.
$appointmentDateAsString = $appointment->getStartDate()?->asDateTimeString();

3- Named arguments 

Named arguments allows us to pass in values to a function, by specifying the value name, so that we don't have to specify their order and we can also skip optional parameters
function SomeFunction(string $a, string $b, ?string $c = null, ?string $d = null) 
{ /* … */ }

SomeFunction (
    b: 'value b', 
    a: 'value a', 
    d: 'value d',

4- static return type

It was already possible to return self prior to PHP8, static wasn't a valid return type. 
Class Example : 

    public function test(): static
        return new static();

5- Match expression

Match is an operator which can return values and it :
•    doesn't require break statements, 
•    can combine conditions, 
•    uses strict type comparisons 
•    doesn't do any type of coercion.
It looks like this:

$matchresult = match($input) {
    0 => "hello",
    '1', '2', '3' => "world",

6- Constructor property promotion

Constructor property promotion is more of syntactic improvement to create value objects or data transfer objects. PHP can now combine them into one Instead of specifying class properties and a constructor.

class Payment 
    public Currency $currency;
    public int $amt;
    public function __construct(
        Currency $currency,
        int $amt,
    ) {
        $this->currency = $currency;
        $this->amt= $amt;
You can write as:
class Payment
    public function __construct(
        public Currency $currency,
        public int $amt,
    ) {}

7- New str_starts_with() and str_ends_with() functions 

Two new functions are now added in the core which were much awaited
str_starts_with('mystring', 'my'); // true
str_ends_with('mystring', 'string'); // true
There are several other improvements that you can go through in official PHP docs. You can’t memorize it all, so the best way to learn them to all is to use them somewhere. So let us start setting up our development environment and see how to create our first page in PHP8.

The Development Environment

PHP Development Environment

Now that we know what to use, we need to create a development environment where we can write code and see results in the development process. We can download all of them manually and that is going to take a long time and many configurations. Many all in one package like XAMPP. When you install it, all the required components from the database to the server are installed and configured automatically and you are good to go with development.
You can choose all of them to install and configure manually but I think first we get the idea of how to create a website or an e-commerce website, precisely, then after that, there are a lot of resources over the internet where you can find all manual steps. Apart from that the automatic installation provides you with many answers like folder structure and which thing to put where in terms of configuration, so when you know this, you can experiment later on with manual configuration.
You can install XAMPP from apachefriends.org and the process is pretty straightforward. You just have to double click the downloaded installer file and the installer guides you through the process. So let us see how to install development environment components like apache server, MySQL, and PHP8 are installed on windows.
I won’t get into the step-by-step screenshots as understand that you are fairly advance to just click next for further steps but I will show you the important screens.
For example, when you get the following screen in the 2nd step when you start with the installation of XAMPP

Installation of XAMPP
 You see that all of the options from the database to language and mail server and even a fake mail (for testing mails) is selected. To install PHP 8, you don’t have to do anything specific as it is already selected. If you don’t want to install Perl, remove it otherwise keep all options ticked if you plan to learn Perl in the future, learning is never bad, right?
Now click next and you will go to the following folder selection screen. You can choose where you want to install, for most of the time default selection is perfectly good to go with.

Installation Folder Selection
 After this just keep clicking next until the installation is started. Wait for the installation to finish and if everything goes well you will see the following screen: 

Completing XAMPP Setup
Here you will see the option of opening the control panel checked. Keep it checked and click finish.
After this you will be asked about language, so you will select English (The US Flag) unless you prefer German. Upon selecting the language, you are presented with the following screen which is the control panel for each component of the development environment.

XAMPP control panel

You can see the benefit here, you have all of the configurations in one place and you are good to go with development. You may face port-related issues in running the apache server here when you click the start button. The required port for apache might already be in use by programs like Skype. You just have to change the port number to the number which is not in use. So if the default port 80 is in use you can change it to 8080. For changing the port number, you just need to click on config and configure httpd.config file and change the port number in the “Listen” segment. The config button in the top right tells you about the ports currently in use and the programs using them.

The Database-Creating Database in MySql

Now that we have created the environment, we will start with our development of the e-commerce website. We will start with the database. The structure of the database must be clear before creating any applications. As of now, we have installed the My SQL along with our XAMPP installation but we need to create a database. With the XAMPP control panel, it is even easier. When Apache and MySql are started, they have highlighted something like the following, and the Admin button is highlighted as well.

Creating Database in MySql
For creating a database click on the Admin button of MySql and the PhpMyAdmin database explorer opens in your default web browser. So let us see how to use MySql through this Php MyAdmin interface: 

Php MyAdmin interface

The interface is simple and you can create a new database by clicking the New button in the left sidebar. Suppose we create a database named “MyEShop”. 

Create a database named “MyEShop”.

So you put the name like the following image and click Create and the new database is created. You can see the new database like following:

Create New database
 Now you can start creating tables by clicking the create table section. Just put the table name and click Go at far right.
Suppose we create a table named Products. It stores some items with price, image, description, etc of a product. This can be used in an e-commerce system, inventory system, and so on.

Start with Code in PHP8

Start with Code in PHP8

Now that we have created the tables, we will need to write some code to connect with the database:
I have used Visual Studio Code. I like the VS Code because of it’s Git integration and Intellisense which helps writing code faster. You can choose your own.

First, we will create a PHP configuration file (config.php) where we can provide details for database connection configuration. Following is the code for config.php. Instead of writing all code in one file, we create different PHP file which is imported to other files depending upon usage. This helps maintaining the separation of concerns in our code and maintenance is easier. We don’t need to find the code to be modified in a sea of code lines. We can pick the specific PHP file and make changes to it if required. For example, if we need to change the database later for some reason or name or password, we will only make changes in Config.php.

/**************************  Config.php ***************************************/

   $DB_HOST = 'localhost'; 
   $DB_NAME = 'myeshop'; 
   $DB_USER = 'root'; 
   $DB_PASS = ''; 

After defining a configuration file, we will create a database connection file which contains the code for connecting the database. It takes the required details from config.php

include 'config.php';

class DB{
    public static $pdo;

    public static function connection(){
                self::$pdo = new PDO('mysql:host='.DB_HOST.'; dbname='.DB_NAME, DB_USER, DB_PASS);
            } catch(PDOException $e){
                echo "Connection Failed";
        return self::$pdo;

    public function prepared($sql){
        return self::connection()->prepare($sql);


You can change details according to your server name and the database name you chose. The file which contains this code will be responsible for all database operations.
The connection function you can see a Syntax like following:
self::$pdo = new PDO('mysql:host='.DB_HOST.'; dbname='.DB_NAME, DB_USER, DB_PASS);
Here PDO is the PHP Data Objects which is the class that provides functions for various database operations.
Now that we have a database and the connection file, let us focus on an e-commerce website on the first page. Generally, what do you see in Amazon or eBay on their first page? A lot of products. So we will show the products there. We will create a product file(product.php).

/************************  Product.php for create class *************************/
class Product{
    private $table = 'products';

public function readAll(){
                    $filter = $_POST['filter'];
                  $sql = "SELECT id, imgUrl, product, price,category FROM products where Product like ? or Description like ? or Category like ? ";
    $sql = "SELECT id, imgUrl, product, price,category FROM products limit 6";
        $stmt = DB::prepared($sql);
        $params = array("%$filter1%","%$filter2%","%$filter3%");
        $result = $stmt->fetchAll();

         if($stmt-> rowCount() > 0){
                         return $result;

You can see that we have a class that has a read All function for getting products for our index page. Here we check if any filter is applied for the database call we store that in the filter and query our database. The select statement uses parameters to avoid any SQL injection attacks which is the most common type of attack when you use any inline query. Avoid using that at all costs.
Apart from that try limiting the use of “*” while selecting records. It might look easy to get all and do operations on the result, but it is a major performance hit and makes your application slow. Always put only those columns which are necessary for a select statement.
We are all set to show our products on the index page, so let’s go ahead and create an index(home) page and write the code for showing all the products in index.php file.

**************** *************  index.php for view product  ************************/
  <?php $product = new Product();
    if(is_array($product->readAll()) || is_object($product->readAll()))
    { ?>
     <?php foreach($product->readAll() as $value){
        echo '<li>
        <div class="single-products">
        <div class="productinfo text-center">
            <a href="product-details.php?prodid='.$value['id'].'" rel="bookmark" title="'.$value['Product'].'">
                <img src="reservation/img/products/'.$value['imgUrl'].'" alt="'.$value['Product'].'" title="'.$value['Product'].'" width="150" height="150" /></a>
                <h2><a href="product-details.php?prodid='.$value['id'].'" rel="bookmark" title="'.$value['Product'].'">'.$value['Product'].'</a></h2>
  <p>Category: '.$row['Category'].'</p>
  <a href="product-details.php?prodid='.$value['id'].'" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>View Details</a>
            } ?>
    <?php }?>

This index code is pretty straightforward. After getting the object of the product class, we check for any null values, and if ok, we loop through the array to create an unordered list with some HTML template.

You can modify the code according to your needs or extend it to any limit, but this gives you an idea about how to write code in PHP and integrate it with HTML design.

Up to now, we have very basic connectivity with our database with a very simple page. IF you have understood and have created the first page, you may want to create more pages. Randomly creating pages is of no use so you might consider taking an example of a system or application, for example, an e-commerce website. Why? Because PHP rules in this segment. There are tonnes of e-commerce solutions written in PHP. For starting with an e-commerce website you will need to create the following pages at least:

  1.         Product details
  2.         Cart Details
  3.         User Registration
  4.         User Login
  5.         Order Confirmation
  6.         Pages for Admin Section
  7.         User Order Details

The pages above are a basic idea of what is minimum for creating an e-commerce website. Obviously, with these pages, you are not going to compete with Amazon or other e-commerce platforms, but it will provide you with a head start.

You can think of adding more pages like an advance admin panel, or more pages like shipping details or return replace functionality, that is up to you.

Hope you enjoyed learning about how to use PHP and MySQL for creating a website and using XAMPP for managing all components of a development environment in one place. For further learning, you can follow the official documentation at PHP.Net or follow PHP The Right way for a good and practical PHP 8 tutorial. Happy coding!!

More knowledge awaits you at KoolStories. Download the app now to discover, connect, learn and grow with like-minded people.


How do I run a PHP file on my desktop?

Open up any Web browser on your desktop and enter "localhost" in the address box. It will open a list of files stored under the "HTDocs" folder on your computer. Click on the link to PHP file and open it to run a script.

How can I create website using PHP and MySQL?

Steps to create website using PHP and MySQL:

1.Connect to a MySQL database with PHP using the PDO (PHP Data Objects) method.
2.Now, create an installer script that will create a new database and a new table with structure.
3.Add entries to a database using HTML form and prepared statements.
4.Filter the database entries and print them to the HTML document in a table.

Is it better to build a website from scratch?

There are advantages of building your website from scratch: There will be no unnecessary code in the development files which means that it won't take any extra time to get downloaded. Only the required lines of code written for the website will be displayed.

Can PHP run without server?

It is possible for you to make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts that are regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows).

Can I use PHP without Apache?

Yes, there are some steps to follow that approach but for that we need a server. Like iis, nginx & many more.