PHP - From Basics to Intermediate, HTML, CSS Integration
PHP - From Basics to Intermediate, HTML, CSS Integration
Rama Nolan
Table of Contents
Chapter 1: INTRODUCTION TO PHP
UNDERSTANDING SERVER-SIDE SCRIPTING AND ITS ROLE IN
WEB DEVELOPMENT
Chapter 2: GETTING STARTED WITH PHP
VARIABLES, DATA TYPES, AND CONSTANTS IN PHP
Chapter 3: CONTROL STRUCTURES IN PHP
BEST PRACTICES FOR WRITING CLEAN AND EFFICIENT PHP
CODE
Chapter 4: WORKING WITH FUNCTIONS IN PHP
UNDERSTANDING SCOPE AND THE USE OF GLOBAL
VARIABLES
Chapter 5: HANDLING FORMS AND USER INPUT IN PHP
CREATING AND PROCESSING HTML FORMS WITH PHP
MANAGING FORM DATA WITH GET AND POST METHODS
Chapter 6: INTRODUCTION TO PHP AND MYSQL
1. PHP Tags:
PHP code is enclosed within special tags that tell the server to process the
enclosed code as PHP. The most common opening and closing tags are:
```php
<?php
// PHP code goes here
?>
```
Anything outside these tags is treated as plain HTML and sent directly to
the client’s browser.
2. Echo Statement:
The `echo` statement is used to output text or HTML to the browser. For
example:
```php
<?php
echo "Hello, World!";
?>
```
This will output the text "Hello, World!" on the web page.
3. Comments:
Comments in PHP can be written in two ways:
- Single-line comments:
```php
// This is a single-line comment
```
- Multi-line comments:
```php
/*
This is a multi-line comment
that spans multiple lines
*/
```
PHP Structure
PHP scripts follow a logical structure similar to other programming
languages. Here's an overview of the key elements:
1. Variables:
Variables in PHP are used to store data that can be used and manipulated
throughout the script. In PHP, variables are denoted by a dollar sign (`$`)
followed by the variable name. For example:
```php
<?php
$greeting = "Hello, World!";
echo $greeting;
?>
```
This will output "Hello, World!" on the web page. PHP variables are
case-sensitive and must start with a letter or underscore, followed by letters,
numbers, or underscores.
2. Data Types:
PHP supports several data types, including:
- Strings: A sequence of characters enclosed in quotes. Example: `"Hello,
World!"`
- Integers: Whole numbers without a decimal point. Example: `42`
- Floats: Numbers with a decimal point. Example: `3.14`
- Booleans: Represents two possible states: `TRUE` or `FALSE`
- Arrays: A collection of values stored in a single variable. Example:
```php
$colors = array("red", "green", "blue");
```
- Objects: Instances of user-defined classes that encapsulate data and
functions.
- NULL: A special data type that represents a variable with no value.
3. Operators:
Operators in PHP are used to perform operations on variables and values.
Common operators include:
- Arithmetic Operators: `+`, `-`, `*`, `/`, `%`
- Assignment Operators: `=`, `+=`, `-=`, `*=`, `/=`
- Comparison Operators: `==`, `!=`, `>`, `<`, `>=`, `<=`
- Logical Operators: `&&`, `||`, `!`
4. Control Structures:
PHP provides several control structures for managing the flow of your
script:
- If-Else Statements: Used to execute code based on conditions.
```php
<?php
$x = 10;
if ($x > 5) {
echo "x is greater than 5";
} else {
echo "x is not greater than 5";
}
?>
```
- Switch Statements: An alternative to multiple if-else statements, useful
when testing a variable against several values.
```php
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Today is Monday";
break;
case "Tuesday":
echo "Today is Tuesday";
break;
default:
echo "Today is not Monday or Tuesday";
}
?>
```
- Loops: Used to repeat a block of code multiple times.
- For Loop:
```php
<?php
for ($i = 0; $i < 5; $i++) {
echo "The value of i is: $i <br>";
}
?>
```
- **While Loop:**
```php
<?php
$i = 0;
while ($i < 5) {
echo "The value of i is: $i <br>";
$i++;
}
?>
```
- Do-While Loop:
```php
<?php
$i = 0;
do {
echo "The value of i is: $i <br>";
$i++;
} while ($i < 5);
?>
```
Variables in PHP
Variables in PHP are used to store data that can be used and manipulated
throughout your script. They are a fundamental part of any programming
language, and PHP is no exception.
1. Declaring Variables:
In PHP, variables are declared with a dollar sign (`$`) followed by the
variable name. For example:
```php
<?php
$name = "John Doe";
$age = 30;
?>
```
2. Assigning Values:
Values are assigned to variables using the `=` operator. The value can be
of any data type, such as a string, integer, or array.
1. String:
A string is a sequence of characters enclosed in single (`'`) or double (`"`)
quotes.
```php
<?php
$greeting = "Hello, World!";
?>
```
2. Integer:
An integer is a non-decimal number, either positive or negative.
```php
<?php
$age = 30;
?>
```
3. Float (Double):
A float is a number with a decimal point or in exponential form.
```php
<?php
$price = 19.99;
?>
```
4. Boolean:
A boolean represents two possible states: `TRUE` or `FALSE`.
```php
<?php
$is_admin = true;
?>
```
5. Array:
An array is a collection of values stored in a single variable. Arrays can
hold multiple values of different data types.
```php
<?php
$colors = array("red", "green", "blue");
?>
```
6. Object:
Objects are instances of classes that encapsulate data and functions
related to that data.
```php
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . ".";
}
}
7. NULL:
The NULL data type represents a variable with no value. It is assigned to
a variable when you want to empty its value.
```php
<?php
$var = null;
?>
```
Constants in PHP
Constants are similar to variables but with three main differences:
- They cannot be changed once they are defined.
- They do not use the `$` sign before them.
- They are defined using the `define()` function.
1. Defining Constants:
```php
<?php
define("SITE_NAME", "MyWebsite");
echo SITE_NAME;
?>
```
In this example, `SITE_NAME` is a constant and cannot be changed
throughout the script.
2. Predefined Constants:
PHP provides many predefined constants like `PHP_VERSION`,
`PHP_OS`, etc., which provide information about the PHP environment.
You should see the output of your script: "Hello, World! The year is 2024."
Chapter 3: CONTROL STRUCTURES IN PHP
Control structures in PHP allow you to control the flow of your program
based on certain conditions. They are fundamental in programming,
enabling you to execute different blocks of code depending on specific
criteria. The primary control structures in PHP include conditional
statements like `if`, `else`, `elseif`, and `switch`. Understanding these
structures is crucial for writing dynamic and responsive PHP applications.
Syntax:
```php
if (condition) {
// code to be executed if the condition is true
}
```
**Example:**
```php
<?php
$age = 20;
Syntax:
```php
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
```
Example:
```php
<?php
$age = 16;
Syntax:
```php
if (condition1) {
// code to be executed if condition1 is true
} elseif (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if none of the conditions are true
}
```
Example:
```php
<?php
$grade = 85;
Syntax:
```php
switch (n) {
case label1:
// code to be executed if n=label1
break;
case label2:
// code to be executed if n=label2
break;
// you can have any number of case statements
default:
// code to be executed if n doesn't match any cases
}
```
Example:
```php
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the work week!";
break;
case "Friday":
echo "Almost the weekend!";
break;
case "Saturday":
case "Sunday":
echo "Weekend!";
break;
default:
echo "Midweek days!";
}
?>
```
In this example, the output will be "Start of the work week!" because `$day`
is "Monday". The `break` statement is used to terminate the case block.
Without `break`, PHP will continue to execute the following cases even if a
match is found.
Ternary Operator:
The ternary operator (`?:`) is a shorthand for the `if...else` statement.
```php
<?php
$score = 75;
$result = ($score >= 50) ? "Pass" : "Fail";
echo $result;
?>
```
This code will output "Pass" if `$score` is 50 or higher, otherwise, it will
output "Fail".
Control structures are essential tools in PHP programming that allow you to
create dynamic and responsive applications. By mastering `if`, `else`,
`elseif`, and `switch` statements, along with best practices for combining
and nesting conditions, you can build powerful, efficient, and maintainable
code. These control structures form the backbone of decision-making in
your scripts, enabling you to handle various scenarios and user inputs
effectively.- Looping structures: for, while, do-while, and foreach.
BEST PRACTICES FOR WRITING CLEAN AND
EFFICIENT PHP CODE
Writing clean and efficient PHP code is crucial for maintaining, scaling, and
securing your applications. Adhering to best practices not only improves
code readability but also enhances performance, reduces bugs, and
simplifies debugging. Here’s a guide to some of the best practices to follow
when writing PHP code:
Example:
```php
<?php
namespace App\Utils;
class Formatter
{
public function formatString(string $input): string
{
return trim(strtolower($input));
}
}
```
The code follows PSR-12 by using proper indentation, namespace
declarations, and consistent function formatting.
Example:
```php
$customerName = "John Doe";
function calculateDiscount($totalAmount) {
// ...
}
```
Here, `customerName` and `calculateDiscount` are clear and descriptive,
making the code easier to understand.
Example:
```php
function calculateTax($amount, $rate) {
return $amount * $rate;
}
Example:
```php
// Calculate the discount based on the customer’s membership level
function calculateDiscount($membershipLevel, $totalAmount) {
if ($membershipLevel === 'Gold') {
return $totalAmount * 0.20; // 20% discount for Gold members
}
return $totalAmount * 0.10; // 10% discount for others
}
```
The comment clarifies the purpose of the function and the specific
discount logic.
Example:
```php
// Caching the result to avoid multiple database queries
$productData = $cache->get('product_data');
if ($productData === null) {
$productData = $db->query("SELECT * FROM products WHERE id
= $productId");
$cache->set('product_data', $productData);
}
```
Example:
```php
try {
$dbConnection = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
error_log($e->getMessage());
die("Database connection failed.");
}
```
Example:
```php
$stmt = $db->prepare("SELECT * FROM users WHERE email =
:email");
$stmt->bindParam(':email', $email);
$stmt->execute();
```
Example:
```php
function calculateTotal($price, $quantity) {
return $price * $quantity;
}
Example:
```php
class DiscountTest extends PHPUnit\Framework\TestCase {
public function testCalculateDiscount() {
$this->assertEquals(80, calculateDiscount('Gold', 100));
}
}
```
Following these best practices when writing PHP code will help you create
clean, efficient, and secure applications. Consistent coding standards,
meaningful naming conventions, reusability, and proper error handling are
just a few ways to improve the quality of your PHP projects. By
incorporating these practices into your workflow, you'll write code that's not
only easier to maintain and scale but also more reliable and performant.
Chapter 4: WORKING WITH FUNCTIONS IN
PHP
Functions are a fundamental building block in PHP, allowing you to group
code into reusable blocks that perform specific tasks. Understanding how to
declare, define, and call functions is essential for writing clean, modular,
and efficient PHP code. In this chapter, we will explore the basics of
working with functions in PHP.
What is a Function?
A function is a named block of code designed to perform a specific task.
Once defined, a function can be called multiple times from different parts of
a program, making your code more modular and reusable. Functions can
take input in the form of parameters and can return a value as output.
Syntax:
```php
function functionName($parameter1, $parameter2, ...) {
// Code to be executed
}
```
Example:
```php
function greetUser($name) {
echo "Hello, " . $name . "!";
}
```
Calling a Function
Once a function is defined, you can call it by using its name followed by
parentheses. If the function requires parameters, you pass them within the
parentheses.
Example:
```php
greetUser("John");
```
Function Parameters
Parameters are variables passed to a function, allowing you to pass
information to it when calling it. PHP functions can have any number of
parameters, and you can set default values for parameters if needed.
Example:
```php
function multiply($a, $b) {
return $a * $b;
}
In this example, the `multiply` function returns the product of `$a` and `$b`,
which is then stored in the variable `$product`.
Example:
```php
function calculateArea($length, $width) {
$area = $length * $width; // $area is a local variable
return $area;
}
Example:
```php
$number = 10;
function addFive() {
global $number;
$number += 5;
}
addFive();
echo $number; // Outputs: 15
```
Anonymous Functions
PHP supports anonymous functions, also known as closures. These are
functions without a name, often used as callback functions or passed as
arguments to other functions.
Example:
```php
$greet = function($name) {
echo "Hello, " . $name . "!";
};
Recursive Functions
A function can call itself, which is known as recursion. Recursive functions
are useful for tasks that can be broken down into smaller, similar tasks.
Example:
```php
function factorial($n) {
if ($n <= 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
echo factorial(5); // Outputs: 120
```
a. Local Scope
When a variable is declared inside a function, it is only accessible within
that function. This is known as local scope. The variable cannot be used
outside the function, ensuring that the function's variables do not interfere
with other parts of the script.
Example:
```php
function calculateSum() {
$a = 5; // Local scope
$b = 10; // Local scope
return $a + $b;
}
echo calculateSum(); // Outputs: 15
// echo $a; // This will cause an error because $a is not accessible outside
the function
```
b. Global Scope
Variables declared outside any function are global variables. These can be
accessed anywhere in the script, except inside functions unless declared as
global within the function.
Example:
```php
$greeting = "Hello, World!"; // Global scope
function displayGreeting() {
// echo $greeting; // This will cause an error because $greeting is not
accessible here
}
displayGreeting();
echo $greeting; // Outputs: Hello, World!
```
c. Static Scope
A static variable is a local variable that does not lose its value when the
function execution is finished. This means that the next time the function is
called, the static variable retains the value it had before.
Example:
```php
function incrementCounter() {
static $counter = 0; // Static scope
$counter++;
echo $counter;
}
incrementCounter(); // Outputs: 1
incrementCounter(); // Outputs: 2
incrementCounter(); // Outputs: 3
```
Example:
```php
$count = 10; // Global variable
function addFive() {
global $count; // Access the global variable
$count += 5;
}
addFive();
echo $count; // Outputs: 15
```
Example:
```php
$_SESSION['user'] = 'JohnDoe';
function displayUser() {
echo $_SESSION['user']; // Outputs: JohnDoe
}
displayUser();
```
```html
<form action="process_form.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<input type="submit" value="Submit">
</form>
```
In this example, the form data will be sent to a PHP script named
`process_form.php` using the POST method.
```php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
```php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if (empty($name)) {
echo "Name is required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.";
} else {
echo "Name: " . htmlspecialchars($name) . "<br>";
echo "Email: " . htmlspecialchars($email) . "<br>";
}
}
```
In this example:
- The `trim()` function is used to remove any unnecessary whitespace from
the input.
- The `empty()` function checks if the name field is empty.
- The `filter_var()` function with `FILTER_VALIDATE_EMAIL` is used to
ensure the email is in a valid format.
```php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
}
$conn->close();
```
In this example, prepared statements are used to securely insert user data
into a MySQL database.
```html
<form action="upload.php" method="post" enctype="multipart/form-
data">
<label for="file">Choose file:</label>
<input type="file" id="file" name="file">
<input type="submit" value="Upload">
</form>
```
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file " . htmlspecialchars(basename($_FILES["file"]
["name"])) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
```
```html
<form action="process_form.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
In this example:
- The `action` attribute is set to `"process_form.php"`, which means the
form data will be sent to this PHP script for processing.
- The `method` attribute is set to `"post"`, ensuring that the data is sent in
the HTTP request body, making it more secure for sensitive information.
```php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
In this script:
- The `$_POST['username']` and `$_POST['password']` are used to retrieve
the form data.
- The `htmlspecialchars()` function is applied to escape special characters
and prevent cross-site scripting (XSS) attacks.
if (empty($username)) {
echo "Username is required.";
} elseif (strlen($password) < 6) {
echo "Password must be at least 6 characters long.";
} else {
echo "Username: " . htmlspecialchars($username) . "<br>";
echo "Password: " . htmlspecialchars($password) . "<br>";
}
}
```
Here:
- The `trim()` function removes any leading or trailing whitespace from the
input.
- `empty()` checks if the `username` field is filled.
- The length of the `password` is validated to ensure it meets a minimum
length requirement.
<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="male"> Male
<input type="radio" id="female" name="gender" value="female">
Female
<label for="hobbies">Hobbies:</label>
<input type="checkbox" name="hobbies[]" value="reading"> Reading
<input type="checkbox" name="hobbies[]" value="travelling">
Travelling
<input type="checkbox" name="hobbies[]" value="sports"> Sports
<label for="country">Country:</label>
<select id="country" name="country">
<option value="usa">USA</option>
<option value="canada">Canada</option>
<option value="uk">UK</option>
</select>
In this script:
- `$_POST['hobbies']` returns an array of selected hobbies, which is then
combined into a string using `implode()`.
- Each value is escaped using `htmlspecialchars()` to ensure safe output.
```html
<form action="upload.php" method="post" enctype="multipart/form-
data">
<label for="file">Upload a file:</label>
<input type="file" id="file" name="file">
<input type="submit" value="Upload">
</form>
```
```php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file " . htmlspecialchars(basename($_FILES["file"]
["name"])) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
```
In this example:
- `$_FILES["file"]["tmp_name"]` contains the temporary file path.
- `move_uploaded_file()` moves the uploaded file to a designated directory.
Use POST over GET for Sensitive Data: The POST method is
more secure as it doesn't expose data in the URL.
Validate and Sanitize Input: Always validate and sanitize user
input to prevent security vulnerabilities.
Escape Output: Use `htmlspecialchars()` to prevent XSS attacks
when displaying user input on a web page.
Use Prepared Statements for Database Interaction: If processing
form data with a database, use prepared statements to prevent SQL
injection.
MANAGING FORM DATA WITH GET AND POST
METHODS
In web development, handling user input through forms is a core
functionality, and understanding how to manage form data with the GET
and POST methods is essential. These two methods determine how form
data is sent to the server, impacting the security, usability, and functionality
of your application.
If the user enters "PHP tutorials" into the search box and submits the form,
the URL might look like this:
```
http://example.com/search.php?query=PHP+tutorials
```
```php
if (isset($_GET['query'])) {
$query = htmlspecialchars($_GET['query']);
echo "You searched for: " . $query;
}
```
In this script:
- `$_GET['query']` retrieves the search term from the URL.
- `htmlspecialchars()` is used to prevent XSS attacks.
```html
<form action="login.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
When this form is submitted, the data is sent to the server without being
visible in the URL.
Here, the `sort` parameter is sent via GET in the URL, while the `query`
parameter is sent via POST.
```php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$query = htmlspecialchars($_POST['query']);
$sort = htmlspecialchars($_GET['sort']);
This script retrieves and processes both GET and POST data.
Security Considerations
- Avoid Sensitive Data in GET Requests: Since GET requests are visible in
the URL and stored in browser history, never use them to transmit sensitive
information.
- Always Sanitize and Validate: Both GET and POST data should be
sanitized and validated to prevent security vulnerabilities like SQL injection
and XSS attacks.
- Use HTTPS: When dealing with sensitive information, ensure that the
form data is transmitted over HTTPS to protect it from being intercepted.
Chapter 6: INTRODUCTION TO PHP AND
MYSQL
MySQL is an open-source relational database management system
(RDBMS) that uses structured query language (SQL) to manage and
manipulate databases. It’s widely used in conjunction with PHP due to its
speed, reliability, and ease of use. MySQL stores data in tables, which are
organized into databases, allowing for efficient data storage and retrieval.
4. Access MySQL:
- Use phpMyAdmin (included in most bundles) to manage your MySQL
databases through a web interface.
- You can also use the MySQL command-line client or other database
management tools.
Using MySQLi:
```php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
```
In this script:
- A new MySQLi object is created using the server name, username,
password, and database name.
- The `connect_error` property is checked to see if the connection was
successful.
Using PDO:
```php
$dsn = "mysql:host=localhost;dbname=my_database";
$username = "root";
$password = "";
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
```
In this script:
- A PDO object is created with the Data Source Name (DSN), username,
and password.
- The connection is checked using a try-catch block to handle any
exceptions.
```php
$sql = "SELECT id, username, email FROM users";
$stmt = $pdo->query($sql);
Using phpMyAdmin:
1. Access phpMyAdmin: Open your web browser and navigate to
`http://localhost/phpmyadmin` (if using a local server like XAMPP or
WAMP).
2. Create a Database:
- Click on the "Databases" tab at the top.
- Enter a name for your database in the "Create database" field.
- Select a collation (usually `utf8_general_ci` is fine for most purposes).
- Click the "Create" button.
Using MySQLi:
The MySQLi extension provides both procedural and object-oriented
interfaces. Here’s how you can connect to a MySQL database using
MySQLi:
Procedural Method:
```php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
```
Object-Oriented Method:
```php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
```
Using PDO:
PDO is a more versatile and secure way to connect to a MySQL database,
as it supports multiple database types. Here’s how you can use PDO:
```php
$dsn = "mysql:host=localhost;dbname=my_database";
$username = "root";
$password = "";
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
```
Explanation:
- `$dsn` (Data Source Name) includes the MySQL server's hostname and
the database name.
- The `PDO` object is created with the DSN, username, and password.
- The `setAttribute` method is used to set the error mode to exception,
which makes debugging easier.
Using phpMyAdmin:
1. Select Your Database: In phpMyAdmin, select the database you just
created from the list on the left.
2. Create a Table:
- Enter a name for your table and specify the number of columns.
- Define the columns (fields) of the table, including data types (e.g.,
`INT`, `VARCHAR`, `TEXT`), length, and attributes (e.g.,
`AUTO_INCREMENT` for primary keys).
- Click "Save" to create the table.
This command creates a table named `users` with four columns: `id`,
`username`, `email`, and `reg_date`.
Using PHP:
```php
$sql = "INSERT INTO users (username, email) VALUES ('john_doe',
'john@example.com')";
Using phpMyAdmin:
1. Select the Table: Choose your table from the left-hand menu.
2. Insert Data:
- Click on the "Insert" tab.
- Fill in the values for each column.
- Click "Go" to insert the data.
Using PDO:
```php
$sql = "SELECT id, username, email FROM users";
$stmt = $pdo->query($sql);
```php
<?php
$hour = date('H');
This script outputs a greeting that changes depending on the current hour.
Example:
```php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Styled PHP Content</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="greeting">
<?php
$hour = date('H');
styles.css:
```css
.greeting {
font-size: 24px;
color: #333;
text-align: center;
margin-top: 50px;
}
```
if ($theme == "dark") {
echo '<link rel="stylesheet" href="dark-theme.css">';
} else {
echo '<link rel="stylesheet" href="light-theme.css">';
}
?>
</head>
<body>
<h1>Welcome to the Website</h1>
</body>
</html>
```
In this example, PHP checks the value of the `$theme` variable and includes
the corresponding CSS file based on the theme selected.
Example:
```php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Dynamic Content Example</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<p>Today’s date is: <?php echo date('Y-m-d'); ?></p>
</body>
</html>
```
In this example, the `date()` function generates the current date, which is
embedded directly into the HTML. When a user visits the page, they see the
date on which they accessed the page.
Here, the greeting changes based on the time of day. This kind of dynamic
content makes the web page feel more personalized and responsive to the
user's context.
In this example, PHP is used to iterate over an array of fruits and generate a
list in HTML. This approach is efficient for displaying a varying number of
items without hardcoding each list element.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
echo "<p>Hello, $name!</p>";
}
?>
</body>
</html>
```
This form allows the user to enter their name, and when submitted, PHP
processes the input and displays a personalized greeting. This dynamic
interaction is a fundamental part of modern web applications.
Example:
```php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Styled PHP Content</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1><?php echo "Welcome to My Stylish PHP Page"; ?></h1>
<p><?php echo "This is a paragraph styled with CSS."; ?></p>
</body>
</html>
```
In this example, `styles.css` is the external stylesheet. The CSS rules
defined in this file will apply to the HTML elements, including those
generated by PHP, making the integration seamless.
Here, the `body` tag’s class is set dynamically based on the value of the
`$theme` variable. The CSS could then define different styles for `.dark`
and `.light` themes, allowing for easy theming.
This approach is useful when you need to apply styles that are calculated or
determined at runtime, such as adjusting layout based on user input or data.
In this example, each list item generated by PHP can be styled uniformly
with CSS rules applied to the `.nav-menu` class. This ensures that the list is
not only functional but also visually appealing.
In the accompanying `styles.css`, you can use media queries to adjust the
styling based on screen size, ensuring that the dynamically generated
content adapts well to different devices.