PHP Introduction

πŸš€ 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!"; 
?>

Try It Now


πŸ“Œ 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>

Try It Now


πŸ“Œ 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."; 
?>

Try It Now


πŸ“Œ PHP Conditional Statements

<?php 
$age = 18; 
if ($age >= 18) {
    echo "You are an adult.";
} else {
    echo "You are a minor.";
}
?>

Try It Now


πŸ“Œ PHP Loops

<?php 
for ($i = 1; $i <= 5; $i++) {
    echo "Number: $i <br>";
}
?>

Try It Now


πŸ“Œ PHP Functions

<?php 
function greet($name) { 
    return "Hello, $name!"; 
} 
echo greet("Alice"); 
?>

Try It Now


πŸ“Œ 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";
?>

Try It Now


πŸ“Œ 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.