π 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.