Learn PHP - A Beginner's Guide

Learn PHP - A Beginner’s Guide

Introduction
PHP (Hypertext Preprocessor) is a widely-used open-source scripting language suited for web development and can be embedded in HTML. This guide will help you get started with PHP, covering fundamental concepts and practical examples.

Prerequisites

  • Basic knowledge of HTML, CSS, and JavaScript
  • A local development environment (XAMPP, WAMP, or LAMP)
  • A code editor (VS Code, Sublime Text, or PHPStorm)

Installation

  1. Download and install XAMPP/WAMP/LAMP
  2. Start Apache and MySQL
  3. Save PHP files in the htdocs (XAMPP) or www (WAMP) directory
  4. Run PHP scripts using http://localhost/yourfile.php

Writing Your First PHP Script

<?php
  echo "Hello, World!";
?>

Save this as hello.php and open it in a browser via http://localhost/hello.php.

PHP Syntax

  • PHP scripts start with <?php and end with ?>
  • Statements end with ;
  • Variables start with $

Variables and Data Types

<?php
  $name = "John"; // String
  $age = 25; // Integer
  $isStudent = true; // Boolean
?>

Operators

  • Arithmetic: +, -, *, /, %
  • Comparison: ==, !=, >, <, >=, <=
  • Logical: &&, ||, !

Conditional Statements

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

Loops
For Loop

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

While Loop

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

Functions

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

Arrays

<?php
  $fruits = array("Apple", "Banana", "Cherry");
  echo $fruits[1]; // Outputs: Banana
?>

Superglobals

  • $_GET, $_POST, $_REQUEST (Handling form data)
  • $_SESSION, $_COOKIE (Managing user sessions)

Connecting to MySQL Database

<?php
  $conn = new mysqli("localhost", "root", "", "testdb");
  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  }
  echo "Connected successfully";
?>

Conclusion
This guide covered PHP basics, including syntax, variables, loops, functions, and database connection. Continue practicing and explore advanced topics like OOP, file handling, and security for deeper understanding.

Happy coding!

1 Like