TUTORIAL 4

PHP Tutorial

Table of Contents

Introduction to PHP

PHP (Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

Setup and Installation

To get started with PHP, you need to install a web server like Apache, and PHP itself. The easiest way to do this is by using a pre-configured software bundle like XAMPP or WAMP.

Download and install XAMPP: https://www.apachefriends.org/index.html

Basic Syntax

PHP scripts are executed on the server, and the result is returned to the browser as plain HTML.

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

Variables and Data Types

Variables in PHP are represented by a dollar sign followed by the name of the variable. PHP supports different data types including strings, integers, floats, arrays, objects, and more.

Example:

<?php
$txt = "Hello, World!";
$int = 123;
$float = 12.34;

echo $txt;
echo $int;
echo $float;
?>

Operators

PHP includes a variety of operators: arithmetic, assignment, comparison, and logical operators.

Example:

<?php
$x = 10;
$y = 20;

$sum = $x + $y; // Arithmetic operator
echo $sum;

$z = ($x == $y); // Comparison operator
echo $z;
?>

Control Structures

PHP supports conditional statements like if, else, and switch, as well as loops like for, while, and foreach.

Example:

<?php
$age = 20;

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

Functions

Functions are blocks of code that can be reused multiple times. PHP has many built-in functions and also allows you to define your own functions.

Example:

<?php
function sayHello() {
    echo "Hello, World!";
}

sayHello();
?>

Arrays

Arrays are used to store multiple values in a single variable. PHP supports indexed arrays, associative arrays, and multidimensional arrays.

Example:

<?php
$colors = array("Red", "Green", "Blue");

echo $colors[0]; // Outputs: Red

$ages = array("Peter" => 35, "Ben" => 37, "Joe" => 43);
echo $ages["Ben"]; // Outputs: 37
?>

Object-Oriented Programming (OOP)

PHP supports OOP and allows the creation of classes, objects, inheritance, and more.

Example:

<?php
class Car {
    public $color;
    public $model;

    public function __construct($color, $model) {
        $this->color = $color;
        $this->model = $model;
    }

    public function message() {
        return "My car is a " . $this->color . " " . $this->model . ".";
    }
}

$myCar = new Car("black", "Volvo");
echo $myCar->message();
?>

Superglobals

PHP provides several superglobals which are built-in variables that are always accessible, regardless of scope. Some of the most common are $_GET, $_POST, $_SERVER, $_SESSION, $_COOKIE.

Example:

<?php
echo $_SERVER['PHP_SELF'];
echo $_POST['name'];
?>

File Handling

PHP has several functions for creating, reading, uploading, and editing files.

Example:

<?php
$file = fopen("test.txt", "w");
fwrite($file, "Hello, World!");
fclose($file);
?>

Database Interaction

PHP can connect to and manipulate databases. The most common database used with PHP is MySQL.

Example:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$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["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>

Advanced Topics

Advanced PHP topics include error handling, sessions, cookies, and more.

Error Handling Example:

<?php
function customError($errno, $errstr) {
    echo "Error: [$errno] $errstr";
}

set_error_handler("customError");

echo($test);
?>

Session Example:

<?php
session_start();
$_SESSION["favcolor"] = "green";
echo "Session variable is set to " . $_SESSION["favcolor"];
?>

Cookie Example:

<?php
setcookie("user", "John Doe", time() + (86400 * 30), "/");
echo "Cookie named 'user' is set!";
?>