What is PHP?
PHP (Hypertext Preprocessor) is an open-source scripting language designed for web development. It is executed on the server and can generate dynamic web pages.
โ Why Learn PHP?
- Easy to learn and use.
- Server-side execution ensures secure code processing.
- Works well with databases like MySQL, PostgreSQL, and MongoDB.
- Supports object-oriented programming (OOP).
- Compatible with almost all web servers and platforms.
๐ Basic PHP Syntax
PHP code is enclosed within <?php ... ?> tags. Below is a simple PHP script that outputs “Hello, World!”
<?php echo "Hello, World!"; ?>
๐ PHP in HTML
PHP can be embedded within HTML to create dynamic web pages:
<!DOCTYPE html>
<html>
<head>
<title>PHP in HTML</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<p>Today's date is: <?php echo date("Y-m-d"); ?></p>
</body>
</html>
๐ PHP Variables
Variables in PHP start with $ and do not require explicit data types.
<?php $name = "John Doe"; $age = 25; echo "My name is $name and I am $age years old."; ?>
๐ PHP Conditional Statements
<?php
$age = 18;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
?>
๐ PHP Loops
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i <br>";
}
?>
๐ PHP Functions
<?php
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice");
?>
๐ PHP and MySQL
PHP is commonly used with MySQL databases. Below is a simple connection example:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
๐ Conclusion
PHP is a powerful scripting language for creating dynamic and interactive web applications. Learning PHP opens opportunities for backend development, CMS creation, and full-stack web projects.