PHP Introduction
PHP (Hypertext Preprocessor) is a popular server-side scripting language designed for web development but also used as a general-purpose language. It’s especially known for its role in creating dynamic web pages and web applications.
Basic PHP Syntax
PHP code is embedded in HTML using the <?php ... ?>
tags. Here’s a simple example:
<!DOCTYPE html>
<html>
<head>
<title>PHP Example</title>
</head>
<body>
<?php
echo "Hello, World!";
?>
</body>
</html>
Output:
When this PHP code is executed on a server, it generates the following HTML:
<!DOCTYPE html>
<html>
<head>
<title>PHP Example</title>
</head>
<body>
Hello, World!
</body>
</html>
Variables
PHP variables start with the $
symbol. Variables do not require explicit declaration and are loosely typed.
<?php
$greeting = "Hello, ";
$name = "Alice";
echo $greeting . $name;
?>
Output:
Hello, Alice
Control Structures
PHP supports standard control structures such as if
, else
, while
, for
, and foreach
.
Example with if
statement:
<?php
$age = 18;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are not an adult.";
}
?>
Output:
You are an adult.
Functions
Functions in PHP are defined using the function
keyword.
Example:
<?php
function greet($name) {
return "Hello, " . $name;
}
echo greet("Bob");
?>
Output:
Hello, Bob
Arrays
PHP supports both indexed and associative arrays.
Indexed Array Example:
<?php
$fruits = array("Apple", "Banana", "Cherry");
echo $fruits[1]; // Outputs: Banana
?>
Associative Array Example:
<?php
$person = array("first_name" => "John", "last_name" => "Doe");
echo $person["first_name"]; // Outputs: John
?>
Connecting to a Database
PHP is often used with MySQL databases. Here’s a simple example of connecting to a MySQL database and querying it:
<?php
$servername = "localhost";
$username = "username";
$password = "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";
// Perform a query
$sql = "SELECT id, name FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Output:
Connected successfully
id: 1 - Name: Alice
id: 2 - Name: Bob
...
These examples provide a glimpse into PHP’s capabilities, from basic syntax and variables to functions and database interactions.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.