PHP and MySQL: A Complete Guide to Building a Dynamic Website
Introduction
Modern websites are more than collections of static HTML pages. Most websites today need to display dynamic content, manage user accounts, process information, and interact with databases. Whether you are building a personal blog, business website, portfolio, or content management system, dynamic functionality plays an important role in creating a useful web experience.
PHP and MySQL are two widely used technologies for developing database-driven websites. PHP handles server-side programming, while MySQL stores, organizes, and manages website information. Together, they provide a practical foundation for developing dynamic web applications.
In this tutorial, we will explore how PHP and MySQL work together and how you can use them to build a functional dynamic website from scratch.
You will learn how to configure a local development environment, create a database, connect PHP to MySQL, perform database operations, display dynamic content, and apply essential security practices.
By the end, you will understand the fundamental workflow behind PHP and MySQL website development.
1. Understanding PHP and MySQL
Before writing code, it is important to understand the technologies used in the development process.
What Is PHP?
PHP is a server-side scripting language designed primarily for web development. It executes on the web server and generates dynamic content that browsers can display.
PHP can be used to:
- - Process HTML forms.
- - Handle user authentication.
- - Communicate with databases.
- - Manage sessions and cookies.
- - Upload and process files.
- - Generate dynamic web pages.
- - Build APIs and web applications.
What Is MySQL?
MySQL is a relational database management system (RDBMS). It stores website information in structured tables containing rows and columns.
For example, a blog website might use MySQL to store:
- - Blog posts.
- - Categories.
- - User accounts.
- - Comments.
- - Website settings.
- - Contact messages.
How Do PHP and MySQL Work Together?
PHP and MySQL perform different but complementary responsibilities.
- A visitor opens a webpage.
- The browser sends a request to the web server.
- PHP processes the request.
- PHP communicates with the MySQL database when necessary.
- MySQL returns the requested information.
- PHP processes the database results and generates HTML.
- The web server sends the generated page to the browser.
This process allows websites to display different information depending on database records and user interactions.
2. Prerequisites and Development Tools
To follow this tutorial, you should have a basic understanding of:
- - HTML for webpage structure.
- - CSS for styling.
- - JavaScript for frontend interactions.
- - PHP fundamentals.
- - Basic SQL queries.
You do not need advanced programming knowledge to begin.
Required Development Tools
You will need:
- XAMPP: XAMPP provides a local development environment containing Apache, PHP, MariaDB, and phpMyAdmin.
- Official website: https://www.apachefriends.org/
- Code Editor: You can use Visual Studio Code, Sublime Text, or another code editor to write PHP and HTML code.
- Web Browser: Google Chrome, Firefox, or Microsoft Edge can be used to test your website.
- phpMyAdmin: phpMyAdmin provides a graphical interface for creating and managing databases.
3. Setting Up Your Local Development Environment
The first step is configuring a local server where your PHP application can run.
Step 1: Install XAMPP
Download XAMPP from its official website and install it on your computer.
During installation, make sure the following components are selected:
- - Apache
- - MySQL (MariaDB)
- - PHP
- - phpMyAdmin
Step 2: Start Apache and MySQL
Open the XAMPP Control Panel and start Apache and MySQL.
Once both services are running, open your browser and visit:
If the installation is successful, the XAMPP dashboard should appear.
Step 3: Create Your Project Directory
Navigate to the XAMPP installation directory and open the
`htdocs` folder.Create a new project directory:
`C:\xampp\htdocs\dynamic-website`Your website will be accessible through:
`http://localhost/dynamic-website/`"Important: Always place your local PHP projects inside the appropriate web server document root."
4. Creating the MySQL Database
Every database-driven website needs a database to store its information.
For this example, we will create a simple content management system that stores blog posts.
Step 1: Open phpMyAdmin
- Visit:`http://localhost/phpmyadmin/`
- Select the option to create a new database.
- Use the following database name: `dynamic_website`
- Choose
`utf8mb4_unicode_ci`as the collation where available.
Step 2: Create a Database Table
Select your newly created database and execute the following SQL query:
```sql
CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
slug VARCHAR(255) NOT NULL UNIQUE,
content TEXT NOT NULL,
status ENUM('draft', 'published')
DEFAULT 'draft',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP
);
```Understanding the Table Structure
- -
`id`: Unique identifier for every post. - -
`title`: Stores the post title. - -
`slug`: Stores the SEO-friendly URL identifier. - -
`content`: Contains the main article content. - -
`status`: Determines whether a post is a draft or published. - -
`created_at`: Records when the post was created. - -
`updated_at`: Records its most recent update.
This structure provides a basic foundation for a dynamic blog website.
5. Connecting PHP to MySQL
After creating the database, the next step is connecting your PHP application to MySQL.
Create a file named `db.php` inside your project directory.
Add the following code:
```php
<?php
$host = "localhost";
$dbname = "dynamic_website";
$username = "root";
$password = "";
try {
$pdo = new PDO(
"mysql:host=$host;dbname=$dbname;charset=utf8mb4",
$username,
$password
);
$pdo->setAttribute(
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
$pdo->setAttribute(
PDO::ATTR_DEFAULT_FETCH_MODE,
PDO::FETCH_ASSOC
);
} catch (PDOException $e) {
error_log($e->getMessage());
die("Unable to connect to the database.");
}
```Understanding the Connection
The PDO class provides a convenient and secure way to communicate with databases.
Here is what the main configuration values represent:
- -
`$host`: Database server address. - - `
$dbname`: Database name. - -
`$username`: Database username. - -
`$password`: Database password. - -
`ERRMODE_EXCEPTION`: Enables exception-based error handling. - -
`FETCH_ASSOC`: Returns database records as associative arrays.
For a default local XAMPP installation, the MySQL username is often `root` and the password is empty. Production environments should use dedicated database credentials.
Test Your Database Connection
Create an
`index.php` file:```php
<?php
require_once "db.php";
echo "Database connection successful!";
?>
```Open: http://localhost/dynamic-website/
If the connection is configured correctly, you should see the success message.
6. Inserting Dynamic Data Into MySQL
Now we will create a form that allows administrators to add new blog posts.
Create a file named
`create.php`.php
<?php
require_once "db.php";
$message = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$title = trim($_POST["title"] ?? "");
$content = trim($_POST["content"] ?? "");
if ($title !== "" && $content !== "") {
$slug = strtolower(
preg_replace('/[^a-zA-Z0-9]+/', '-', $title)
);
$slug = trim($slug, '-');
$stmt = $pdo->prepare(
"INSERT INTO posts
(title, slug, content, status)
VALUES (:title, :slug, :content, 'published')"
);
$stmt->execute([
":title" => $title,
":slug" => $slug,
":content" => $content
]);
$message = "Post created successfully!";
} else {
$message = "Please complete all required fields.";
}
}
?>
<h2>Create a New Post</h2>
<p><?= htmlspecialchars($message) ?></p>
<form method="POST">
<input
type="text"
name="title"
placeholder="Post title"
required
>
<br><br>
<textarea
name="content"
placeholder="Write your content..."
required
></textarea>
<br><br>
<button type="submit">Publish Post</button>
</form>
How the Insertion Process Works
- The administrator enters a post title and content.
- The form submits the information using the POST method.
- PHP retrieves and validates the submitted values.
- A URL-friendly slug is generated.
- PDO prepares the SQL query.
- The execute method inserts the information into MySQL.
You should also implement duplicate-slug handling and CSRF protection before using this functionality in a production application.
7. Retrieving and Displaying Dynamic Content
A dynamic website should automatically display information stored in its database.
To retrieve blog posts, create a file named
`posts.php`.```php
<?php
require_once "db.php";
$stmt = $pdo->query(
"SELECT id, title, slug, content, created_at
FROM posts
WHERE status = 'published'
ORDER BY created_at DESC"
);
$posts = $stmt->fetchAll();
?>
<h1>Latest Articles</h1>
<?php foreach ($posts as $post): ?>
<article>
<h2>
<?= htmlspecialchars($post['title']) ?>
</h2>
<p>
<?= htmlspecialchars(
substr($post['content'], 0, 150)
) ?>...
</p>
<a href="post.php?slug=<?= urlencode($post['slug']) ?>">
Read More
</a>
</article>
<hr>
<?php endforeach; ?>
```Understanding the SELECT Query
The SQL `SELECT` statement retrieves information from a database table.
In this example:
- -
`WHERE status = 'published'`displays published posts only. - -
`ORDER BY created_at DESC`sorts the newest posts first. - -
`fetchAll()`retrieves the matching records. - -
`foreach`displays each post individually.
This is how a website can automatically display newly published content without manually creating another HTML page.
8. Creating Dynamic Single Post Pages
A professional blog should provide a separate page for every article.
Instead of creating hundreds of individual PHP files, we can use one reusable template.
Create
`post.php`:```php
<?php
require_once "db.php";
$slug = $_GET['slug'] ?? '';
$stmt = $pdo->prepare(
"SELECT * FROM posts
WHERE slug = :slug
AND status = 'published'
LIMIT 1"
);
$stmt->execute([
":slug" => $slug
]);
$post = $stmt->fetch();
if (!$post) {
http_response_code(404);
die("Article not found.");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
<?= htmlspecialchars($post['title']) ?>
</title>
</head>
<body>
<article>
<h1>
<?= htmlspecialchars($post['title']) ?>
</h1>
<p>
Published:
<?= htmlspecialchars($post['created_at']) ?>
</p>
<div>
<?= nl2br(htmlspecialchars($post['content'])) ?>
</div>
</article>
<a href="posts.php">Back to Articles</a>
</body>
</html>
```Now every article can be accessed using a different slug: http://localhost/dynamic-website/post.php?slug=my-first-articlehttp://localhost/dynamic-website/post.php?slug=my-first-article
For a production website, Apache URL rewriting can be used to create cleaner URLs such as:
Clean URLs improve readability and make website URLs easier to share.
9. Updating Existing Database Records
A content management system should allow administrators to modify existing information.
SQL uses the
`UPDATE` statement to change database records.The following example demonstrates the basic operation:
```php
<?php
require_once "db.php";
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$id) {
die("Invalid post ID.");
}
$stmt = $pdo->prepare(
"SELECT * FROM posts WHERE id = :id"
);
$stmt->execute([
":id" => $id
]);
$post = $stmt->fetch();
if (!$post) {
die("Post not found.");
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$title = trim($_POST['title'] ?? '');
$content = trim($_POST['content'] ?? '');
if ($title !== "" && $content !== "") {
$stmt = $pdo->prepare(
"UPDATE posts
SET title = :title,
content = :content
WHERE id = :id"
);
$stmt->execute([
":title" => $title,
":content" => $content,
":id" => $id
]);
header("Location: posts.php");
exit;
}
}
?>
```
The complete editing page would also include an HTML form populated with the existing post values.
When the administrator submits the updated information, PHP executes the UPDATE query and saves the changes.
## 10. Deleting Database Records
The final CRUD operation is deleting information.
SQL uses the `DELETE` statement for this purpose.
Example:
```php
<?php
require_once "db.php";
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
http_response_code(405);
exit("Method not allowed.");
}
$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
if (!$id) {
die("Invalid post ID.");
}
$stmt = $pdo->prepare(
"DELETE FROM posts WHERE id = :id"
);
$stmt->execute([
":id" => $id
]);
header("Location: posts.php");
exit;
?>
```For security, deleting records should require administrator authorization and CSRF validation. A confirmation dialog can also help prevent accidental deletion.
11. Understanding CRUD Operations
CRUD represents the four fundamental operations used in most database-driven applications

Almost every content management system, business application, and e-commerce platform relies on these operations.
Once you understand CRUD, you have learned one of the most important foundations of backend web development.
12. Recommended PHP Project Structure
Organizing your project properly makes development easier and more efficient.
A basic structure could look like this:
```text
dynamic-website/
โ
โโโ index.php
โโโ db.php
โโโ posts.php
โโโ post.php
โโโ create.php
โโโ edit.php
โโโ delete.php
โ
โโโ assets/
โ โโโ css/
โ โ โโโ style.css
โ โโโ js/
โ โ โโโ script.js
โ โโโ images/
โ
โโโ includes/
โ โโโ header.php
โ โโโ footer.php
โ โโโ functions.php
โ
โโโ admin/
โโโ login.php
โโโ dashboard.php
```As the project grows, you can separate application logic into models, controllers, and views.
This separation improves maintainability, readability, and scalability.
13. Essential PHP and MySQL Security Practices
Security should be considered from the beginning of website development, not added only after deployment.
Here are some important practices:
Use Prepared Statements
Never directly concatenate user input into SQL queries. Use PDO or MySQLi prepared statements.
### Validate Input
Validate all incoming data on the server, even if frontend JavaScript validation is already implemented.
### Escape Output
Use
`htmlspecialchars()` when displaying untrusted text inside HTML to reduce Cross-Site Scripting (XSS) risks.### Hash User Passwords
Never store passwords as plain text.
PHP provides built-in password hashing functions:
```php
$hash = password_hash(
$password,
PASSWORD_DEFAULT
);
```Verify passwords using:
```php
if (password_verify($password, $hash)) {
echo "Authentication successful.";
}```Implement Authentication and Authorization
Protect administrative pages and ensure users can only access actions they are authorized to perform.
### Protect Against CSRF
Use unique CSRF tokens for sensitive forms, including post creation, editing, and deletion.
### Use HTTPS
Enable HTTPS on production websites to protect information transmitted between browsers and servers.
### Secure Configuration Files
Keep database credentials outside publicly accessible directories when possible. Never commit production credentials to public repositories.
### Maintain Regular Backups
Back up both website files and database records regularly.
These practices help create more reliable and secure PHP applications.
14. Common Problems and Their Solutions
Beginners often face configuration and coding problems while developing PHP and MySQL applications.
Some common issues include:

Always read error messages carefully. Debugging is an essential part of becoming a professional developer.
15. Taking Your Dynamic Website to the Next Level
The example in this tutorial provides a basic foundation. However, professional websites usually require additional functionality.
After completing the basic project, consider implementing:
- User Authentication: Registration, login, logout, password recovery, and role-based permissions.
- Admin Dashboard: A centralized interface for managing website content and settings.
- Category Management: Organize articles into meaningful categories.
- Image Uploads: Allow administrators to upload featured images and other media.
- Search Functionality: Enable visitors to search for articles and other content.
- Pagination: Display large collections of records across multiple pages.
- SEO Management: Add custom meta titles, meta descriptions, canonical URLs, and structured data.
- Responsive Design: Make the website work smoothly on mobile phones, tablets, and desktop computers.
- Performance Optimization: Use database indexing, optimized queries, caching, and image compression.
- Deployment: Configure a production server, environment variables, database credentials, HTTPS, and automated backups.
These features will help transform a basic PHP application into a complete web solution.
## Conclusion
PHP and MySQL remain a practical combination for building dynamic websites and database-driven web applications.
Throughout this tutorial, we explored the essential development process, from installing XAMPP and creating a database to connecting PHP with MySQL and implementing CRUD operations.
We also covered dynamic content rendering, project organization, prepared statements, and essential security practices.
Understanding these fundamentals gives you the foundation to develop more advanced applications, including personal blogs, business websites, portfolio platforms, and complete content management systems.
However, reading tutorials alone is not enough. The most effective way to improve your development skills is to apply what you learn by building real projects.
Start with a simple dynamic website, experiment with different features, and gradually develop your own complete application.
Ready to build your next project? Put these concepts into practice, explore more backend development techniques, and continue improving your PHP and MySQL skills.