1. Introduction to PHP
PHP (Hypertext Preprocessor) is a server-side scripting language used to create dynamic web pages. It is widely used with HTML and databases like MySQL.
Why Use PHP?
-
Runs on all major operating systems (Windows, macOS, Linux).
-
Can be embedded into HTML.
-
Supports databases like MySQL.
-
Open-source and widely supported.
2. Setting Up PHP
To run PHP, you need:
-
XAMPP or WAMP (Local Server)
-
A text editor (VS Code, Sublime, Notepad++, etc.)
After installing XAMPP/WAMP, start Apache and MySQL, and store your files in the htdocs
folder (www
for WAMP).
3. Basic PHP Syntax
PHP code is written inside <?php ... ?>
tags.
<?php
echo "Hello, World!";
?>
Save this as index.php
and open it in your browser ( http://localhost/index.php
).
4. Variables in PHP
<?php
$name = "John";
$age = 25;
echo "My name is $name and I am $age years old.";
?>
-
Variables start with
$
-
Strings use
"
or'
-
Concatenation is done using
.
(dot)
5. Data Types
PHP supports:
-
String (
$text = "Hello";
) -
Integer (
$number = 25;
) -
Float (
$price = 12.99;
) -
Boolean (
$isValid = true;
) -
Array (
$colors = ["Red", "Green", "Blue"];
)
6. Conditional Statements
<?php
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
?>
7. Loops in PHP
For Loop
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i <br>";
}
?>
While Loop
<?php
$i = 1;
while ($i <= 5) {
echo "Number: $i <br>";
$i++;
}
?>
8. Functions in PHP
<?php
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice");
?>
9. Forms and User Input
Create an HTML form:
<form method="POST" action="process.php">
<input type="text" name="username" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
Handle it in process.php
:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['username'];
echo "Welcome, $name!";
}
?>
10. Connecting to a Database (MySQL)
<?php
$conn = new mysqli("localhost", "root", "", "test_db");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully!";
?>
11. Fetching Data from Database
<?php
$result = $conn->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo "User: " . $row['name'] . "<br>";
}
?>
12. Including External Files
Use include
or require
to import common files:
<?php include 'header.php'; ?>
Next Steps
Now that you know the basics, try practicing HTML on https://www.w3schools.com/
If you need further support, feel free to ask here.