Objective of learning PHP
- Set up a PHP environment (XAMPP or WAMP).
- Understand basic PHP syntax, variables, and operators.
- Use conditional statements and loops in PHP.
- Handle and validate forms.
- Implement a lab exercise to create and display user data.
What is PHP?
- PHP (Hypertext Preprocessor): A server-side scripting language for web development.
- Explain its role in dynamic websites.
Setting Up a PHP Environment
Install the latest version of the xampp server.
PHP Basics: Syntax, Variables, and Operators
Syntax:
PHP tags: <?php … ?>
Variables:
Declaring variables: $variable_name = value;
Operators:
- Arithmetic: +, -, *, /, %.
- Assignment: =, +=, -=.
- Comparison: ==, !=, >, <.
- Logical: &&, ||, !.
- Examples (5 minutes):
<?php $num1 = 10; $num2 = 20; $sum = $num1 + $num2; echo "The sum of $num1 and $num2 is $sum."; ?>
Conditional Statements:
- if
- if-else,
- if-elseif-else
- switch
Example:
<?php $age = 18; if ($age >= 18) { echo "You are eligible to vote."; } else { echo "You are not eligible to vote."; } ?>
Loops:
- for
- while
- do-while
- foreach
<?php for ($i = 1; $i <= 5; $i++) { echo "Number: $i<br>"; } ?>
Hands-On Practice:
Write a PHP script to print all even numbers between 1 and 20 using a loop.
Form Handling and Validation
Form Handling:
$_GET and $_POST superglobals for accessing form data.
<form action="process.php" method="POST"> Name: <input type="text" name="name"> <button type="submit">Submit</button> </form>
PHP script (process.php):
<?php $name = $_POST['name']; echo "Hello, $name!"; ?>
Validation:
- Ensure required fields are filled.
- Sanitize user input using htmlspecialchars().
Example:
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = htmlspecialchars($_POST['name']); if (!empty($name)) { echo "Hello, $name!"; } else { echo "Name is required!"; } } ?>
Lab Exercise:
Create a PHP form to capture user data (e.g., name, email, and age) and display it on another page.