HTML to PHP Overview
In PHP, HTML code is mixed with PHP code to generate dynamic pages. When a user visits a PHP page, the server processes the PHP code, executes it, and then returns the resulting HTML to the browser.
Basic Example: HTML to PHP
Here's a simple example where PHP is embedded within an HTML document to dynamically generate content.
Example: Displaying Dynamic Content with PHP
php
<?php
// PHP code that sets a variable
$greeting = "Hello, welcome to our website!";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML to PHP Example</title>
</head>
<body>
<!-- PHP code inserted into HTML -->
<h1><?php echo $greeting; ?></h1>
<p>This is a simple PHP page that displays dynamic content.</p>
</body>
</html>
Explanation:
The PHP block (<?php ... ?>) is used to execute PHP code on the server.
The PHP code inside the block sets a variable $greeting.
The PHP echo statement is used to print the content of the $greeting variable inside the <h1> tag.
When this page is requested, the PHP code is executed on the server, and the final result (HTML) is sent to the browser.
Example: Using PHP to Process Form Data and Display Dynamic HTML
PHP can also be used to handle form submissions and dynamically modify HTML content based on user input.
Example: Simple Form Submission
php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect form data
$name = htmlspecialchars($_POST['name']); // Sanitize input
$email = htmlspecialchars($_POST['email']);
// Dynamic PHP content (confirmation message)
$message = "Thank you for submitting, $name! We'll contact you at $email.";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML to PHP Form Example</title>
</head>
<body>
<h1>Contact Form</h1>
<!-- Display confirmation message if the form was submitted -->
<?php if (isset($message)): ?>
<p><?php echo $message; ?></p>
<?php endif; ?>
<!-- Form for submitting name and email -->
<form method="POST">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Explanation:
When the form is submitted, it sends data to the same page (POST request).
The PHP code checks if the form was submitted by verifying the $_SERVER["REQUEST_METHOD"] is POST.
It then collects the user's name and email, sanitizes the input using htmlspecialchars(), and displays a dynamic confirmation message using PHP.
The form allows users to submit their name and email, and once submitted, the page reloads and displays a message containing the submitted data.
Example: Using PHP with Loops to Generate HTML
PHP can also be used to generate large amounts of HTML dynamically by looping through arrays or databases.
Example: Dynamic HTML List from Array
php
<?php
// Define an array of fruits
$fruits = ["Apple", "Banana", "Orange", "Mango", "Peach"];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML to PHP Dynamic List</title>
</head>
<body>
<h1>Fruit List</h1>
<ul>
<!-- Loop through the fruits array and generate <li> items -->
<?php foreach ($fruits as $fruit): ?>
<li><?php echo $fruit; ?></li>
<?php endforeach; ?>
</ul>
</body>
</html>
Explanation:
The PHP foreach loop is used to iterate over the $fruits array.
For each element in the array, the loop generates an <li> tag with the fruit name.
The result is a dynamically generated list of fruits displayed on the webpage.
Using PHP with Databases
PHP is often used in conjunction with databases (e.g., MySQL or PostgreSQL) to generate dynamic HTML content based on data stored in a database.
Example: Displaying Data from a MySQL Database
php
<?php
// Database connection
$conn = new mysqli("localhost", "root", "", "test_db");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch data from the database
$result = $conn->query("SELECT name, email FROM users");
// Display fetched data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p>Name: " . $row["name"] . " - Email: " . $row["email"] . "</p>";
}
} else {
echo "No results found";
}
// Close the connection
$conn->close();
?>
Explanation:
This PHP script connects to a MySQL database (test_db).
It retrieves data from a users table, specifically the name and email columns.
The PHP script loops through the results and generates HTML <p> tags to display each user's name and email.
The connection to the database is closed after the data is fetched.
Summary: HTML to PHP Concepts
Embedding PHP in HTML: PHP code is embedded within an HTML document using <?php ... ?> tags. The PHP code is executed on the server, and the output is sent as HTML to the client.
Dynamic Content: PHP can generate dynamic HTML based on server-side logic, form data, or database content.
Form Handling: PHP can process form data and generate dynamic content based on user input.
Database Interaction: PHP can interact with databases to fetch data and generate HTML content dynamically.
Why Use PHP with HTML?
Dynamic Content: PHP can dynamically generate HTML based on data, user input, or logic.
Server-Side Logic: PHP allows complex server-side operations, like interacting with databases, sending emails, and handling file uploads.
Content Personalization: PHP can personalize content for each user by customizing the HTML based on session variables or user authentication.