How To Build A Website

Website Is Built!
Website done 🙂

I’m sure there are a million articles on the internet about how to build a website.

I was always curious about how to build my own website, especially after being a professional developer for a few years. My professional work always had me developing and iterating over existing pieces of work or working within an established framework.

So I set out to answer my own question using the expertise I gained (and a lot of persistence!).

This post will go through the things I learned and how I ultimately was able to get a website up and running that has some really cool functionality. The steps I took were:

  1. Thinking about what I wanted the website to do
  2. Picking a web site host and buying a domain
  3. Building the website using the tools provided by the host
  4. Iteration!!!

The website build I will talk about is a website built using HTML/CSS, Javascript/jQuery, PHP, and SQL. These are not the most modern technologies on the market today, but they work extremely well for building a website for single-user interaction.

The Idea

I can’t help you think of what you want on your website, but you are only limited by your imagination. You can use this post to build your own blog, resume page, portfolio, or even a database that you can use to keep track of what you want (this is what I ended up building).

One caveat. If you’re looking to build a product that you plan to have used by more than one user at a time, this blog won’t be enough!

The Host

Once you have an idea of what you want to build, you’ll need to buy a domain and get a website host. The domain is the URL you want the website to be linked to and the host provides you with the infrastructure to get up and running.

I ended up going with Hostinger, a web host that was well priced for the features they offered. I was able to buy a domain and the package I bought came with databases to use and a few other features that came in handy during the building process.

The First Step

After I bought the domain and setup my account with the host, I looked at their tools and started from scratch:

I just wanted to go to a URL and have it show a message I created.

I’ll go through how I accomplished this simple, but important step, below.

Iteration, Iteration, Iteration

After I got my message on the screen, I was able to work as fast as I could figure things out. I was able to add interactions, colors, data, and link to a database! A full-fledged website was born!

Sounds simple, right?

Breaking Down A Website

Any website that you are building will have 4 major components:

  1. The visuals, or front-end (HTML/CSS)
  2. User interactions and the results of those actions (Javascript and jQuery)
  3. The logic of displaying information and handling data (PHP)
  4. The database to save persistent information (SQL)

Your website idea will dictate if you need all of these, but any website idea, from a portfolio page, blog, or application would need something like the above to function.

HTML/CSS

So, let’s start with the basics: how do we get a message to show up on our website?

Your webhost tools should have some sort of file management system, which is what your code is. The code that makes up your website is simply files of text you wrote in a file system that then represents the website.

For my case, when I logged into my Hostinger account, I saw a File Manager that looked like this:

Hostinger File Manager

I went into the public_html folder and created my html file:

Website HTML

I called my file ‘about.html’ and I put the text shown above in the file. When I went to my url/about.html:

Website Displaying HMTL

That’s what I saw in my browser!

It may not seem like much, but I honestly get blown away every time something like the above happens. It’s really amazing that you can build something publicly accessible (or not, your choice!) and see it on your browser.

Let’s say you want a little pizzazz on your text. This is where the styling, or CSS, comes in. I want the text to be bigger and I want the text to be blue. I added the following to my about.html file and:

Website HTML With CSS
Website HTML and CSS

My website was on its way!!!

I added a CSS class to my HTML, in between the head tags and style tags. Then, I gave my text some <p> tags and gave them the class I created, ‘styling.’ You can read thousands and thousands of articles on CSS functions, features, and techniques, but now you can leverage them on your own website, in any way you see fit!

Javascript/jQuery

Once I had some content on the website, the next thing I wanted was a simple user-interaction. Say I clicked on the text ‘My Website.’ It would be nice to see something happen. This is where Javascript and jQuery come into play.

Javascript is a language that allows you to run code on the browser. This code can do any number of things, including manipulating elements on your website. The HTML written above is translated into elements:

Website In Chrome Inspector

jQuery is a language that allows you to do the same, but it also allows you to query the elements on your page. Querying elements gives you the ability to pick specific elements and interact with them.

Say I wanted to click on ‘My Website’ and show a message acknowledging it was clicked. First, I have to embed jQuery into my page:

<head>
  <style>
    .styling{
      color: blue;
      font-size: 72px;
    }
  </style>
  <script src="https://code.jquery.com/jquery-latest.min.js"></script>
</head>

You can checkout what jQuery is all about here. For our purposes, just know that jQuery allows us to select elements and manipulate them. I wanted to have something happen when I clicked on ‘My Website.’ With jQuery, I can grab the element by searching for tags, styles, or attributes, but I can also do the simplest case: search by id.

<body>
    <p id="mywebsite" class="styling">
        My Website
    </p>
    <script>
        $('#mywebsite').on('click', function(){
            $('body').html('I clicked here!')
        });
    </script>        
</body>

I gave the ‘My Website’ <p> tag an id and then wrote a little jQuery for when I click on it:

jQuery On Click Before
Before clicking
jQuery On Click After
After clicking!

Pretty cool! The code updated out content based on our action. You can write almost anything you can think of using this structure. jQuery also works for many events, not just ‘click.’ Take a look at some of the other actions you can trigger events off of and combine it with Javascript and jQuery to build dynamic, sophisticated apps!

Database Calls

Now that you have a way to get content to show on the page and a way to have events, let’s try saving some data. In the previous step, our event fired on click to change some text on our website. Now, let’s use a button to keep a running count of how many times we have pressed it, regardless of if we left and came back to the website.

First, I will place a button on the page:

<body>
    <p id="mywebsite" class="styling">
        My Website
    </p>
    <button id="counter">
        Click Me!
    </button>
    <script>
        $('#mywebsite').on('click', function(){
            $('body').html('I clicked here!')
        });
    </script>        
</body>
Website With Button

Every time we click this button, I want to update a counter that saves the number of times it was clicked. In Hostinger, I have access to a Database panel:

Hostinger Database

I am able to created a database hosted in the same location as my webpage. I created a username and password for my database and then I went to phpMyAdmin. This is the tool I used to configure the specifics of the database itself.

When using a database, the key things to consider are what columns you want, what type of data the columns hold, and if there are any unique properties associated to any of those columns, like being non-nullable or unique. For my purposes, I will only need a simple integer column to keep track of a count:

phpMyAdmn New Column

Now, we need to use PHP to connect to the database and get information from it in our front-end HTML code. A great thing about PHP is html an be embedded in it, and the PHP code will with it, but it will not show up on the front-end (it will simply run the logic to control what is displayed on the front-end).

To use PHP, I change my ‘about.html’ file to ‘about.php’ and then made a connection to the database:

<body>
    <?php 
        $servername = "localhost";
        $database = [database_name];
        $username = [database_username];
        $password = [database_password]; 

        $conn = mysqli_connect($servername, $username, $password, $database);

?>        
    <p id="mywebsite" class="styling">
        My Website
    </p>
    <button id="counter">
        Click Me!
    </button>
    <script>
        $('#mywebsite').on('click', function(){
            $('body').html('I clicked here!')
        });
    </script>        
</body>

PHP is written inline with your HTML and it is always enclosed in ‘<?php ?>’ tags.

Now that the connection is made, we ca also get the value of counter and render it:

<body>
    <?php 
        $servername = "localhost";
        $database = [database_name];
        $username = [database_username];
        $password = [database_password];  

        $conn = mysqli_connect($servername, $username, $password,  $database);

    ?>        
    <p id="mywebsite" class="styling">
        My Website
    </p>

    <button id="counter">
        Click Me!
    </button>
    <?php
        $getCounter = "SELECT * FROM [database_name] WHERE ObjectId = 13 LIMIT 1";
        $counterResult = mysqli_query($conn, $getCounter);
        while($row = mysqli_fetch_array($counterResult)){ 
    ?>
    <p>You have clicked this button<?php echo $row['Counter']?> times.</p>
    <?php } ?>
    <script>
        $('#mywebsite').on('click', function(){
            $('body').html('I clicked here!')
        });
    </script>        
</body>

Note that PHP can be broken up and mixed in with the HTML to render content dynamically. Notice how the while loop is iterating over the result of the SQL query and then rendering values in the HTML. If this query returned more than one row, it would render the value in the <p> tag for each row returned by the query.

We are going to store the counter value in a row in the database with a known ObjectId. I already created the row in this table, but you would insert a new row if there was no row in the table. I am them using PHP to get the value of the row, and then specifically get the value of the counter column:

Website With PHP and SQL

Making A Database Call Through AJAX

Finally, I need to have the button update the database and return the information I want to display, the value of Counter. To do this, we need to make an AJAX call when the button is clicked. AJAX is a framework for making calls to a database asynchronously, meaning the call will happen and return a value without needing to wait specificaly for that call.

AJAX calls have some config and will point to a PHP file on the server, which will then make a database operation and return the information needed to the front-end. First, I set the structure of my AJAX call:


    <script>
        $('#mywebsite').on('click', function(){
            $('body').html('I clicked here!')
        });
        $('#counter').on('click', function(){
            var request = $.ajax({
                type: 'post',
                url: 'updateCounter.php',
                data: {
                    dataSentBack: 'I am data'
                },              
                success: function(result){
                    if(result!= ''){$('#counterstatus').html(result);}
                },              
                error: function (error){
                    console.log(error);
                }              
            });                
        })
    </script>        

I add the following code to my script tag and I gave the <p> tag that displayed the counter message an id. Now, when clicked, the button will call a file called updateCounter.php and pass it some data, which I have placed for thoroughness. I am not passing anything back that is needed, but if you were, you could follow this format to pass values to the backend.

Then, updateCounter.php will return a result or an error. If a result is returned, the HTML of the <p> tag is replaced with the value of result. I will build the HTML in the backend if successful. If there is an error, the console will log it for debugging.

Now let’s create updateCounter.php on the backend:

Hostinger Create New PHP File
<?php
if (isset($_POST)) {

 $servername = "localhost"; 
 $database = [database_name]; 
 $databaseusername = [databaseuser_name]; 
 $password = [database_password];
 $conn = mysqli_connect($servername, $databaseusername, $password, $database);
 $data =  $_POST['dataSentBack']; 

 $sqlrow = "SELECT * FROM [database_name] WHERE ObjectId = 13 LIMIT 1";
 $resultrow = mysqli_query($conn, $sqlrow); 
 $resultrow = mysqli_query($conn, $sqlrow); 
 while($rowcurrent = $resultrow->fetch_assoc()) {     
     $counter = $rowcurrent['Counter']; 
 } 

 if($counter == null){     
     $counter = 1; 
 } 
 else{     
     $counter = $counter + 1; 
 } 

 $sqlrow = "UPDATE * [database_name] SET Counter = $counter";      
 $resultrow = mysqli_query($conn, $sqlrow); 
 $sqlrow = "UPDATE [database_name] SET Counter = $counter";      
 $resultrow = mysqli_query($conn, $sqlrow); 
 $html = 'You have clicked this button '.$counter.' times.'; echo $html;
}
?>

In PHP, you join string with ., which took me a bit to get used to. You can see this on the last line where the $html variable is returned.

This code is getting value of counter from the row I stored it in, incrementing it if it is not null, an then returning an HTML string for the front-end to display. When I click on it:

AJAX Before Click
AJAX After Click

Amazing! I the clicked the button 10 more times and revisited the page and:

Website With Database Persistence

It remembered!

With these techniques, you should be able to get started making a fairly complicated website!

Leave a Reply

%d bloggers like this: