Understanding the Fundamentals of Web Development

Raihan Fadhil
8 min readJun 29, 2024

--

Introduction to Web Programming

Web development is a dynamic field that continuously evolves with technological advancements. As a developer, it’s essential to understand the fundamentals of web programming to create effective and responsive applications. In this article, we’ll explore various critical topics in web programming, from basic introductions to modern frameworks. Let’s dive in!

History and Development of the Web

Web 1.0: The first generation of the web, characterized by static pages that allowed users to read information only.
Web 2.0: The web became more interactive and dynamic with the rise of social media, blogs, and wikis.
Web 3.0: Further development with the application of AI and machine learning, making the web smarter and more contextual.

HTML (HyperText Markup Language)
HTML is the standard language for creating web pages. Basic HTML elements include tags for page structure such as <html>, <head>, <title>, and <body>, as well as content elements like paragraphs (<p>), headings (<h1> to <h6>), links (<a>), images (<img>), and lists (<ul>, <ol>, <li>).

Introduction to HTML & CSS

In this section, we delve deeper into understanding HTML and CSS, which are used to create and design web pages.

Basic HTML Structure

An HTML document starts with the <!DOCTYPE html> declaration followed by <html>, <head>, and <body> elements. The <head> element contains metadata, while the <body> contains content displayed on the web page.

Text Elements

Headings: Use <h1> to <h6> tags to create titles with varying levels of importance.
Paragraphs: The <p> tag is used for paragraphs.
Horizontal Lines: The <hr> tag is used to create horizontal lines.
Text Formatting: Tags like <b>, <i>, <u>, <strong>, and <em> are used for bold, italic, underline, and emphasized text.

Multimedia Elements

Images: The <img> tag is used to insert images with the src attribute specifying the image source.
Audio and Video: The <audio> and <video> tags are used to embed audio and video files.

Understanding CSS

CSS (Cascading Style Sheets) is a language used to design and manage the appearance of web pages. CSS can be applied in three ways:

Inline CSS: Using the style attribute directly within HTML elements.
Internal CSS: Using the <style> tag within the <head> element.
External CSS: Linking to an external CSS file using the <link> tag.

CSS Selectors and Properties

Selectors: Used to select HTML elements to style. Common selectors include tag selectors, class selectors (.classname), and ID selectors (#idname).
Properties: Define the visual aspects of elements. Examples include color, background-color, font-size, margin, padding, and border.

Example Program Code

HTML & CSS

<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Welcome to My Web Page</h1>
<p>This is a paragraph of text.</p>
<a href="https://example.com">Visit Example</a>
<img src="image.jpg" alt="Example Image">
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</body>
</html>
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}

h1 {
color: #333;
}

p {
font-size: 16px;
}

a {
color: blue;
text-decoration: none;
}

img {
max-width: 100%;
}

PHP Fundamentals

PHP (Hypertext Preprocessor) is a server-side programming language used to create dynamic web pages. PHP runs on the server, and the output is sent to the user’s browser as HTML.

Variables and Data Types

PHP supports various data types, such as integers, floats, strings, booleans, arrays, and objects. Variables in PHP start with a $ sign.

Operators

PHP provides operators for mathematical, comparison, logical, and other operations. Examples include +, -, *, /, %, ==, !=, >, <, &&, ||, and !.

Control Structures

PHP supports control structures such as conditions (if, else, elseif, switch) and loops (for, while, do-while, foreach).

Example Program Code

<?php
// Variables and Data Types
$name = "John";
$age = 30;
$isStudent = true;

// Conditional Statement
if ($age > 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}

// Loop
for ($i = 0; $i < 5; $i++) {
echo "Number: $i<br>";
}
?>

Forms and Database Access with PHP

Forms are HTML elements used to collect user input. Through forms, users can interact with the web and submit data via various input elements like text fields, checkboxes, radio buttons, text areas, and submit buttons.

Creating Forms

Three key aspects to understand when creating a form:

METHOD: Determines how form data is sent. There are two methods: GET and POST.
ACTION: Specifies the script’s location that will process the form data.
SUBMIT BUTTON: A button that triggers the submission of form data.

Form Validation

Form validation is performed on the client side before the data is sent to the server for further processing. This ensures the form is properly filled out.

GET vs. POST Methods

POST Method: Sends data directly to the action without displaying it in the URL. Data is stored in the $_POST variable.
GET Method: Displays data in the URL before being captured by the action. Data is stored in the $_GET variable.

Database Connection with PHP

MySQL databases use relational techniques to connect tables within the database. MySQL is a popular choice for use with PHP due to its free GPL license and reliability.

Basic Database Connection Steps

Create a connection to the database.
Create a query.
Execute the query.
Fetch the query results.
Repeat steps 2–4 until all necessary data is retrieved.
Close the database connection.
PHP and MySQLi

PHP offers several ways to interact with MySQL databases:

MySQL Extension (deprecated): Supports structural coding.
MySQLi Extension: Supports both structural and object-oriented coding.
PDO (PHP Data Object): Supports only object-oriented coding.
Model-View-Controller (MVC)
MVC is an architecture that separates business logic (model), presentation logic (view), and controllers. This separation simplifies the development and maintenance of complex web applications.

MVC Goals

Improve code organization.
Separate business logic from the presentation.
Facilitate development and maintenance.

Example Program Code

HTML Form

<form action="process.php" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<input type="submit" value="Submit">
</form>

Database Connection

<?php
// Database connection using MySQLi
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Query execution
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"] . "<br>";
}
} else {
echo "No results found.";
}

$conn->close();
?>

PHP State, Session, Cookies

The web is stateless, meaning each client request to the server is treated independently without retaining information from previous requests. To address this, mechanisms like sessions and cookies are used to store and manage user information across pages or sessions.

Sessions

Definition: Sessions are a mechanism for storing user data on the server side.
Usage: Used to store login information, user preferences, shopping carts, and user activity tracking.
Management: Session data is stored on the server and identified using a session ID sent to the client as a cookie.

Cookies

Definition: Cookies are small data files stored on the user’s computer by the web browser.
Usage: Used to remember user preferences, login information, and track user activity across sessions.
Management: Cookies have expiration dates and can be set to automatically delete after a certain period.

Example Program Code

Sessions

<?php
session_start();
$_SESSION['username'] = "JohnDoe";
echo "Session set.";
?>

Cookies

<?php
setcookie("user", "JohnDoe", time() + (86400 * 30), "/");
echo "Cookie set.";
?>

File Handling in PHP

Basic File Operations

Opening and Closing Files: Open files for reading or writing and close them after use.
Reading File Contents: Retrieve content from a file for display or processing.
Writing to Files: Save data to a file, either by overwriting old content or appending new content.
Deleting Files: Remove files that are no longer needed.

Directory Operations

Creating and Deleting Directories: Manage folder structures for file storage.
Reading Directory Contents: Get lists of files and folders in a directory for further processing.

Example Program Code

<?php
// Write to a file
$file = fopen("example.txt", "w");
fwrite($file, "Hello, world!");
fclose($file);

// Read from a file
$file = fopen("example.txt", "r");
echo fread($file, filesize("example.txt"));
fclose($file);
?>

Databases PHP Data Object (PDO)

Introduction

PDO is a PHP extension providing a uniform interface for accessing different database types. PDO supports databases like MySQL, PostgreSQL, and SQLite, offering high flexibility and portability.

Database Connection with PDO

Creating a Connection: Use the PDO class to connect to a database.
Error Handling: Use exceptions to handle connection or query errors.

Prepared Statements

Prepared statements enhance database query security and performance. By separating query logic from user input, prepared statements protect applications from SQL injection attacks.

Example Program Code

<?php
// Database connection using PDO
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(['id' => 1]);
$user = $stmt->fetch();

echo "Name: " . $user['name'];
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>

Introduction to Frameworks and Bootstrap

Frameworks in Web Development

Frameworks provide a foundation for building web applications, speeding up development with ready-to-use libraries and modules.

Bootstrap

Bootstrap is a popular front-end framework for developing responsive web applications. Developed by Twitter, Bootstrap offers tools for building consistent and aesthetic web interfaces.

Bootstrap Features

Grid System: A flexible grid system for creating responsive layouts.
UI Components: A collection of ready-to-use UI components like buttons, forms, cards, and navbars.
CSS Utilities: A set of utility classes to simplify styling elements.

Example Program Code

Bootstrap

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1 class="text-center">Welcome to My Site</h1>
<button class="btn btn-primary">Click Me</button>
</div>
</body>
</html>

Model-View-Controller (MVC)

Introduction:

MVC is a software design pattern that separates an application into three main components: Model, View, and Controller.

  • Model: Contains business logic and application data.
  • View: Displays data and UI.
  • Controller: Manages user input and updates the Model and View.

Objectives of MVC:

  • Improve code organization.
  • Separate business logic from presentation.
  • Facilitate development and maintenance.

Components of MVC:

  • Model: Stores application data and ensures data integrity and validity.
  • View: Presents data from the Model to users and can be dynamically updated.
  • Controller: Controls data flow between the Model and View, processes user input, and updates the Model.

How MVC Works:

  1. Users interact with the View.
  2. The Controller receives input from the View.
  3. The Controller updates the Model based on the input.
  4. The View retrieves the latest data from the Model and displays it.

MVC Implementation:

Many popular frameworks implement MVC, such as Laravel (PHP), Django (Python), and Ruby on Rails (Ruby).

Example Program Code

Route (web.php)

Route::get('/users', [UserController::class, 'index']);

Controller (UserController.php)

public function index() {
$users = User::all();
return view('users.index', compact('users'));
}

Model (User.php)

class User extends Model {
protected $fillable = ['name', 'email'];
}

View (index.blade.php)

@foreach($users as $user)
<p>{{ $user->name }}</p>
@endforeach

JavaScript and AJAX

Introduction

JavaScript: A cross-platform programming language that can run on the client (browser) and server (Node.js).
AJAX (Asynchronous JavaScript and XML): A technique for communicating with the server without reloading the page.

JavaScript Usage

Adding interactivity to web applications, such as form validation, autocomplete suggestions, and showing/hiding page elements.

Writing JavaScript

Internal: JavaScript code is written directly within the HTML document.
External: JavaScript code is written in a separate file and linked to the HTML document.

DOM (Document Object Model)

JavaScript can access every element on a web page via the DOM, using functions like document.getElementById(), document.getElementsByTagName(), document.getElementsByClassName(), document.querySelector(), and document.querySelectorAll().

Introduction to AJAX

AJAX allows web applications to make asynchronous requests in the background. Asynchronous communication is implemented with the XMLHttpRequest object or Fetch API, commonly using XML or JSON data.

Advantages and Disadvantages of AJAX

Advantages:
Responsive, enhancing user experience.
Reduces bandwidth usage.
Supports asynchronous processing/communication.

Disadvantages:
Browser compatibility issues.
Security concerns.
Increased server load.

Example Program Code

JavaScript

document.getElementById('myButton').addEventListener('click', function() {
alert('Button clicked!');
});

Ajax

fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => console.error('Error:', error));

Conclusion

Mastering web programming requires a deep understanding of various concepts and technologies. From basic HTML and CSS to PHP and modern frameworks, each element plays a vital role in creating functional and attractive web applications. By studying these topics, you can build responsive, dynamic web applications ready to face future challenges. Keep learning and experimenting to become a better web developer!

--

--