PHP What is OOP?
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or functions that perform
operations on the data, while object-oriented programming is about creating
objects that contain both data and functions.
Object-oriented programming has several advantages over procedural
programming:
OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes
the code easier to maintain, modify and debug
OOP makes it possible to create full reusable applications with less code
and shorter development time
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition
of code. You should extract out the codes that are common for the application,
and place them at a single place and reuse them instead of repeating it.
PHP - What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented programming.
Look at the following illustration to see the difference between class and
objects:
class
Fruit
objects
Apple
Banana
Mango
So, a class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the properties and
behaviors from the class, but each object will have different values for the
properties.
OOP Case
Let's assume we have a class named Fruit. A Fruit can have properties like
name, color, weight, etc. We can define variables like $name, $color, and
$weight to hold the values of these properties.
When the individual objects (apple, banana, etc.) are created, they inherit all
the properties and behaviors from the class, but each object will have different
values for the properties.
Define a Class
A class is defined by using the class keyword, followed by the name of the class
and a pair of curly braces ({}). All its properties and methods go inside the
braces:
Define Objects
Classes are nothing without objects! We can create multiple objects from a
class. Each object has all the properties and methods defined in the class, but
they will have different property values.
Objects of a class is created using the new keyword.
In the example below, we add two more methods to class Fruit, for setting and
getting the $color property:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit();
$apple->set_name('Apple');
$apple->set_color('Red');
echo "Name: " . $apple->get_name();
echo "<br>";
echo "Color: " . $apple->get_color();
?>
PHP - The $this Keyword
The $this keyword refers to the current object, and is only available inside
methods.
Look at the following example:
Example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
?>
So, where can we change the value of the $name property?
1. Inside the class (by adding a set_name() method and use $this):
Example
<?php
class Fruit {
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
echo $apple->name;
?>
PHP - instanceof
You can use the instanceof keyword to check if an object belongs to a specific
class:
Example
<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>
PHP - What is a Constructor?
A constructor allows you to initialize an object's properties upon creation of the
object.
If you create a __construct() function, PHP will automatically call this function
when you create an object from a class.
Notice that the construct function starts with two underscores (__)!
PHP - What is Inheritance?
Inheritance in OOP = When a class derives from another class.
The child class will inherit all the public and protected properties and methods
from the parent class. In addition, it can have its own properties and methods.
An inherited class is defined by using the extends keyword.
Let's look at an example:
Example
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
// Strawberry is inherited from Fruit
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>
Example Explained
The Strawberry class is inherited from the Fruit class.
This means that the Strawberry class can use the public $name and $color
properties as well as the public __construct() and intro() methods from the Fruit
class because of inheritance.
The Strawberry class also has its own method: message().
Understanding Visibility Scope in PHP Object
In PHP, the visibility scope of properties and methods within a class determines
how they can be accessed. PHP provides three levels of visibility: `public`,
`protected`, and `private`. Each visibility level has different implications on
how and where these members can be accessed:
1. **Public**:
- Properties or methods declared as `public` can be accessed from
anywhere: from inside the class, from subclasses (child classes), and from
outside the class.
- Syntax:
```php
class MyClass {
public $publicProperty;
public function publicMethod() {
// Code
```
2. **Protected**:
- Properties or methods declared as `protected` can be accessed within the
class itself and by inheriting (subclass) classes. They cannot be accessed from
outside the class.
- Syntax:
```php
class MyClass {
protected $protectedProperty;
protected function protectedMethod() {
// Code
```
3. **Private**:
- Properties or methods declared as `private` can only be accessed within
the class that defines them. They are not accessible from outside the class, nor
by inheriting classes.
- Syntax:
```php
class MyClass {
private $privateProperty;
private function privateMethod() {
// Code
}
```
### Example to Illustrate Visibility Scopes
```php
<?php
class BaseClass {
public $publicProperty = "Public";
protected $protectedProperty = "Protected";
private $privateProperty = "Private";
public function publicMethod() {
echo "Public Method\n";
protected function protectedMethod() {
echo "Protected Method\n";
private function privateMethod() {
echo "Private Method\n";
public function accessMethods() {
$this->publicMethod(); // Accessible
$this->protectedMethod(); // Accessible
$this->privateMethod(); // Accessible
class SubClass extends BaseClass {
public function accessMethods() {
$this->publicMethod(); // Accessible
$this->protectedMethod(); // Accessible
// $this->privateMethod(); // Not accessible
$object = new BaseClass();
$object->publicMethod(); // Accessible
// $object->protectedMethod(); // Not accessible
// $object->privateMethod(); // Not accessible
$subObject = new SubClass();
$subObject->publicMethod(); // Accessible
// $subObject->protectedMethod(); // Not accessible
// $subObject->privateMethod(); // Not accessible
// Accessing properties
echo $object->publicProperty; // Accessible
// echo $object->protectedProperty; // Not accessible
// echo $object->privateProperty; // Not accessible
```
### Key Points:
- **Public** members can be accessed from anywhere.
- **Protected** members can only be accessed within the class itself and its
child classes.
- **Private** members can only be accessed within the class that defines them.
Understanding these scopes helps you design more secure and encapsulated
object-oriented code, ensuring that internal implementation details are
protected and only exposed when necessary.
Understanding PHP class STATIC attributes and method in PHP
In PHP, `static` attributes and methods belong to the class itself rather than to
any particular instance of the class. This means that they can be accessed
without creating an instance of the class. Here’s a detailed explanation:
### Static Attributes (Properties)
Static attributes are shared among all instances of a class. They can be
accessed using the `::` operator.
- **Declaration**:
```php
class MyClass {
public static $staticProperty = "Static Value";
```
- **Access**:
```php
// Accessing static property without an instance
echo MyClass::$staticProperty; // Outputs: Static Value
// Changing static property value
MyClass::$staticProperty = "New Value";
echo MyClass::$staticProperty; // Outputs: New Value
```
### Static Methods
Static methods can be called without creating an instance of the class. They
cannot access non-static properties or methods directly but can access static
properties and methods.
- **Declaration**:
```php
class MyClass {
public static function staticMethod() {
echo "Static Method Called";
```
- **Access**:
```php
// Calling static method without an instance
MyClass::staticMethod(); // Outputs: Static Method Called
```
### Example
Here’s a complete example demonstrating the use of static properties and
methods:
```php
<?php
class Counter {
// Static property to hold the counter value
private static $count = 0;
// Static method to increment the counter
public static function increment() {
self::$count++;
// Static method to get the current count
public static function getCount() {
return self::$count;
// Incrementing the counter without creating an instance
Counter::increment();
Counter::increment();
Counter::increment();
// Getting the current count
echo Counter::getCount(); // Outputs: 3
?>
```
### Key Points:
1. **Static Properties**:
- Declared using the `static` keyword.
- Shared across all instances of the class.
- Accessed using `ClassName::$property`.
2. **Static Methods**:
- Declared using the `static` keyword.
- Can be called without creating an instance of the class.
- Accessed using `ClassName::method()`.
3. **Accessing Static Members**:
- Use the `self` keyword to access static properties and methods within the
same class.
- Use `parent` to access static properties and methods from a parent class.
4. **Limitations**:
- Static methods cannot access non-static properties or methods.
- Static properties cannot be accessed using `$this`.
### Example with Inheritance
Static properties and methods can also be inherited by subclasses:
```php
<?php
class Base {
protected static $name = "Base";
public static function getName() {
return static::$name; // Note the use of 'static::' for late static binding
class Derived extends Base {
protected static $name = "Derived";
}
// Accessing static method from Base class
echo Base::getName(); // Outputs: Base
// Accessing static method from Derived class
echo Derived::getName(); // Outputs: Derived
?>
```
In this example, `static::$name` uses late static binding, meaning it refers to
the `static` property of the called class rather than the class where the method
is defined.
Static members are useful for storing data or functionality that is common to all
instances of a class, such as counters, configurations, or utility methods.
Understanding Constructor Method in PHP Object
In PHP, a constructor is a special method that is automatically called when an
instance of a class is created. Constructors are typically used to initialize the
object's properties or perform any setup procedures required when the object is
instantiated.
### Syntax
In PHP, the constructor method is defined using the `__construct` keyword.
Here’s the basic syntax:
```php
class MyClass {
public function __construct() {
// Initialization code here
```
### Example
Here’s a simple example that demonstrates how to use a constructor to initialize
an object’s properties:
```php
<?php
class Person {
public $name;
public $age;
// Constructor method
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
public function displayPerson() {
echo "Name: " . $this->name . "\n";
echo "Age: " . $this->age . "\n";
// Creating an instance of the Person class
$person1 = new Person("John Doe", 30);
$person1->displayPerson();
// Outputs:
// Name: John Doe
// Age: 30
?>
```
In this example, the `Person` class has a constructor that takes two
parameters, `$name` and `$age`. When a new `Person` object is created,
these parameters are passed to the constructor, which initializes the object’s
properties.
### Key Points
1. **Automatic Invocation**: The constructor is automatically called when an
object of the class is created using the `new` keyword.
2. **Parameter Passing**: Constructors can take parameters to initialize the
object with specific values.
3. **Initialization**: The primary use of a constructor is to initialize the
properties of an object.
### Constructor in Inheritance
When dealing with inheritance, the child class can call the parent class’s
constructor using the `parent` keyword.
#### Example
```php
<?php
class Animal {
public $name;
// Constructor method
public function __construct($name) {
$this->name = $name;
}
public function display() {
echo "Animal: " . $this->name . "\n";
class Dog extends Animal {
public $breed;
// Constructor method
public function __construct($name, $breed) {
// Calling the parent class constructor
parent::__construct($name);
$this->breed = $breed;
public function display() {
parent::display(); // Call the parent class method
echo "Breed: " . $this->breed . "\n";
}
// Creating an instance of the Dog class
$dog = new Dog("Buddy", "Golden Retriever");
$dog->display();
// Outputs:
// Animal: Buddy
// Breed: Golden Retriever
?>
```
In this example:
- The `Animal` class has a constructor that initializes the `name` property.
- The `Dog` class extends the `Animal` class and has its own constructor to
initialize both `name` and `breed`.
- The `Dog` constructor calls the `Animal` constructor using
`parent::__construct($name)` to ensure that the `name` property is properly
initialized.
### Constructor Overriding
In a child class, the constructor of the parent class can be overridden. However,
you should always ensure that necessary initializations from the parent class
are not missed by explicitly calling the parent constructor if needed.
### Best Practices
1. **Initialization**: Use constructors to set up the initial state of an object.
2. **Consistency**: Ensure that constructors in child classes call the parent
class’s constructor if the parent class requires certain initializations.
3. **Error Handling**: Implement appropriate error handling within
constructors to handle invalid initialization parameters gracefully.
Constructors are a fundamental part of object-oriented programming in PHP,
enabling the proper initialization of objects and ensuring that they are ready to
be used immediately after creation.
PHP FILE HANDLING
Let's go through each of these topics one by one to understand PHP file
handling, functions, and operations like opening, reading, copying, and moving
files.
### PHP File Handling
PHP provides various functions to handle files and perform operations such as
reading, writing, copying, and moving files. File handling is essential for any
web application that needs to store or retrieve data from files.
### Working with PHP File Functions
PHP offers a variety of functions for file handling. Here are some of the
commonly used file functions:
- `fopen()`: Opens a file or URL.
- `fclose()`: Closes an open file pointer.
- `fread()`: Reads from an open file.
- `fwrite()`: Writes to an open file.
- `file_get_contents()`: Reads the entire file into a string.
- `file_put_contents()`: Writes a string to a file.
- `copy()`: Copies a file.
- `rename()`: Renames or moves a file.
- `unlink()`: Deletes a file.
### Opening a File with PHP
To open a file in PHP, you use the `fopen()` function. The `fopen()` function
requires two arguments: the file name and the mode in which you want to open
the file.
Common file modes:
- `'r'`: Read-only. Starts at the beginning of the file.
- `'r+'`: Read/Write. Starts at the beginning of the file.
- `'w'`: Write-only. Opens and truncates the file; or creates a new file if it
doesn't exist.
- `'w+'`: Read/Write. Opens and truncates the file; or creates a new file if it
doesn't exist.
- `'a'`: Write-only. Opens and writes to the end of the file or creates a new file
if it doesn't exist.
- `'a+'`: Read/Write. Preserves file content by writing to the end of the file.
#### Example
```php
<?php
$file = fopen("example.txt", "r");
if ($file) {
echo "File opened successfully.";
fclose($file);
} else {
echo "Failed to open file.";
?>
```
### Reading File Content
To read the content of a file, you can use `fread()` or `file_get_contents()`.
#### Using `fread()`
```php
<?php
$file = fopen("example.txt", "r");
if ($file) {
$content = fread($file, filesize("example.txt"));
fclose($file);
echo $content;
} else {
echo "Failed to open file.";
?>
```
#### Using `file_get_contents()`
```php
<?php
$content = file_get_contents("example.txt");
if ($content !== false) {
echo $content;
} else {
echo "Failed to read file.";
?>
```
### Copying and Moving Files Using PHP
#### Copying Files
To copy a file, use the `copy()` function. It takes two arguments: the source
file and the destination file.
```php
<?php
$source = "example.txt";
$destination = "example_copy.txt";
if (copy($source, $destination)) {
echo "File copied successfully.";
} else {
echo "Failed to copy file.";
?>
```
#### Moving (Renaming) Files
To move or rename a file, use the `rename()` function. It also takes two
arguments: the current file name and the new file name (or path).
```php
<?php
$oldName = "example_copy.txt";
$newName = "new_example.txt";
if (rename($oldName, $newName)) {
echo "File moved/renamed successfully.";
} else {
echo "Failed to move/rename file.";
?>
```
### Deleting Files
To delete a file, use the `unlink()` function.
```php
<?php
$file = "new_example.txt";
if (unlink($file)) {
echo "File deleted successfully.";
} else {
echo "Failed to delete file.";
?>
```
### Summary
- **Opening Files**: Use `fopen()` with appropriate modes.
- **Reading Files**: Use `fread()` for reading chunks of a file or
`file_get_contents()` for reading the whole file.
- **Copying Files**: Use `copy()` to create a copy of a file.
- **Moving/Renaming Files**: Use `rename()` to move or rename a file.
- **Deleting Files**: Use `unlink()` to delete a file.
These functions provide a robust way to handle files in PHP, enabling you to
create, read, update, and delete files as needed in your web applications.
PHP FOLDER HANDLING
PHP provides various functions to handle directories (folders) and perform
operations such as creating, reading, copying, moving, and deleting directories.
These operations are essential for managing files and directories within a web
application.
### Creating Folders with PHP
To create a folder in PHP, you can use the `mkdir()` function. This function
creates a new directory.
#### Syntax
```php
bool mkdir(string $pathname, int $mode = 0777, bool $recursive = false,
resource $context = null)
```
- `$pathname`: The directory path to create.
- `$mode`: The permissions (default is 0777).
- `$recursive`: If set to true, it will create nested directories specified in the
path.
- `$context`: A valid context resource (optional).
#### Example
```php
<?php
$dir = "new_folder";
if (!file_exists($dir)) {
if (mkdir($dir, 0777, true)) {
echo "Directory created successfully.";
} else {
echo "Failed to create directory.";
} else {
echo "Directory already exists.";
?>
```
### Reading Folder Contents
To read the contents of a directory, you can use the `scandir()` function or the
`opendir()` and `readdir()` functions.
#### Using `scandir()`
```php
<?php
$dir = "new_folder";
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file !== '.' && $file !== '..') {
echo $file . "\n";
} else {
echo "Directory does not exist.";
?>
```
#### Using `opendir()` and `readdir()`
```php
<?php
$dir = "new_folder";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if ($file !== '.' && $file !== '..') {
echo $file . "\n";
closedir($dh);
} else {
echo "Directory does not exist.";
?>
```
### Copying, Moving, and Deleting a Folder
#### Copying a Folder
PHP doesn't have a built-in function to copy a directory with its contents. You'll
need to create a custom function to recursively copy all files and subdirectories.
```php
<?php
function copyDirectory($src, $dst) {
$dir = opendir($src);
@mkdir($dst);
while (false !== ($file = readdir($dir))) {
if (($file !== '.') && ($file !== '..')) {
if (is_dir($src . '/' . $file)) {
copyDirectory($src . '/' . $file, $dst . '/' . $file);
} else {
copy($src . '/' . $file, $dst . '/' . $file);
closedir($dir);
$source = "new_folder";
$destination = "new_folder_copy";
copyDirectory($source, $destination);
?>
```
#### Moving a Folder
To move or rename a folder, you can use the `rename()` function.
```php
<?php
$oldName = "new_folder";
$newName = "moved_folder";
if (rename($oldName, $newName)) {
echo "Directory moved successfully.";
} else {
echo "Failed to move directory.";
?>
```
#### Deleting a Folder
To delete a folder with its contents, you can create a custom function to
recursively delete all files and subdirectories.
```php
<?php
function deleteDirectory($dir) {
if (!file_exists($dir)) {
return true;
if (!is_dir($dir)) {
return unlink($dir);
foreach (scandir($dir) as $item) {
if ($item === '.' || $item === '..') {
continue;
if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
return false;
return rmdir($dir);
$dir = "moved_folder";
if (deleteDirectory($dir)) {
echo "Directory deleted successfully.";
} else {
echo "Failed to delete directory.";
?>
```
### Uploading File with PHP
To upload files with PHP, you need to create an HTML form and handle the file
upload on the server side.
#### HTML Form
```html
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>
```
#### PHP File (upload.php)
```php
<?php
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($targetFile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
// Allow certain file formats
if ($imageFileType !== "jpg" && $imageFileType !== "png" && $imageFileType
!== "jpeg" && $imageFileType !== "gif") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
// Check if $uploadOk is set to 0 by an error
if ($uploadOk === 0) {
echo "Sorry, your file was not uploaded.";
// If everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile))
{
echo "The file " .
htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been
uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
?>
```
### Summary
- **Creating Folders**: Use `mkdir()` to create directories.
- **Reading Folder Contents**: Use `scandir()` or `opendir()` and `readdir()`
to read directory contents.
- **Copying Folders**: Create a custom function to recursively copy directories
and their contents.
- **Moving Folders**: Use `rename()` to move directories.
- **Deleting Folders**: Create a custom function to recursively delete
directories and their contents.
- **Uploading Files**: Use HTML forms to upload files and handle the upload
with PHP by using `$_FILES` and `move_uploaded_file()`.
These functions and techniques provide robust file and directory management
capabilities in PHP.
Working with Dates and Time in PHP
PHP provides a variety of functions and classes for working with dates and
times.
#### Getting the Current Date and Time
You can use the `date()` function to get the current date and time.
```php
<?php
echo date('Y-m-d H:i:s'); // Outputs the current date and time
?>
```
#### Formatting Dates
The `date()` function allows you to format dates.
```php
<?php
echo date('l jS \of F Y h:i:s A'); // Outputs something like: Monday 2nd of July
2024 12:34:56 PM
?>
```
#### DateTime Class
The `DateTime` class provides more flexibility and powerful features for date
and time manipulation.
```php
<?php
$date = new DateTime();
echo $date->format('Y-m-d H:i:s'); // Outputs the current date and time
?>
```
#### Modifying Dates
You can modify dates using the `DateTime` class.
```php
<?php
$date = new DateTime();
$date->modify('+1 day');
echo $date->format('Y-m-d H:i:s'); // Outputs the date and time one day from
now
?>
```
#### Comparing Dates
You can compare dates using the `DateTime` class.
```php
<?php
$date1 = new DateTime('2024-07-01');
$date2 = new DateTime('2024-07-02');
if ($date1 < $date2) {
echo "$date1 is earlier than $date2";
} else {
echo "$date1 is later than $date2";
?>
```
### Working with Pagination
Pagination is the process of dividing a large dataset into smaller chunks
(pages). Here’s a basic example using PHP and MySQL.
#### Example: Paginating Database Results
1. **Database Structure**:
```sql
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);
```
2. **Connecting to the Database**:
```php
<?php
$conn = new mysqli('localhost', 'username', 'password', 'database');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
?>
```
3. **Fetching and Displaying Data with Pagination**:
```php
<?php
$limit = 10; // Number of entries to show per page
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$offset = ($page - 1) * $limit;
$total_results = $conn->query("SELECT COUNT(*) FROM users")-
>fetch_row()[0];
$total_pages = ceil($total_results / $limit);
$result = $conn->query("SELECT * FROM users LIMIT $offset, $limit");
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - " . $row['email'] . "<br>";
// Pagination controls
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
?>
```
### Creating a CRUD Application
A CRUD application allows you to create, read, update, and delete records in a
database.
#### Example: CRUD with PHP and MySQL
1. **Database Structure**:
```sql
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10, 2) NOT NULL
);
```
2. **Connecting to the Database**:
```php
<?php
$conn = new mysqli('localhost', 'username', 'password', 'database');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
```
3. **Create (Insert) Operation**:
```php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$price = $_POST['price'];
$stmt = $conn->prepare("INSERT INTO products (name, price) VALUES
(?, ?)");
$stmt->bind_param('sd', $name, $price);
$stmt->execute();
$stmt->close();
echo "New product created successfully";
?>
<form method="post">
Name: <input type="text" name="name"><br>
Price: <input type="text" name="price"><br>
<input type="submit" value="Add Product">
</form>
```
4. **Read (Select) Operation**:
```php
<?php
$result = $conn->query("SELECT * FROM products");
while ($row = $result->fetch_assoc()) {
echo $row['id'] . " - " . $row['name'] . " - " . $row['price'] . "<br>";
?>
```
5. **Update Operation**:
```php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['id'];
$name = $_POST['name'];
$price = $_POST['price'];
$stmt = $conn->prepare("UPDATE products SET name = ?, price = ?
WHERE id = ?");
$stmt->bind_param('sdi', $name, $price, $id);
$stmt->execute();
$stmt->close();
echo "Product updated successfully";
// Fetching product data for the update form
if (isset($_GET['id'])) {
$id = $_GET['id'];
$result = $conn->query("SELECT * FROM products WHERE id = $id");
$product = $result->fetch_assoc();
?>
<form method="post">
<input type="hidden" name="id" value="<?php echo $product['id']; ?>">
Name: <input type="text" name="name" value="<?php echo
$product['name']; ?>"><br>
Price: <input type="text" name="price" value="<?php echo
$product['price']; ?>"><br>
<input type="submit" value="Update Product">
</form>
```
6. **Delete Operation**:
```php
<?php
if (isset($_GET['delete'])) {
$id = $_GET['delete'];
$stmt = $conn->prepare("DELETE FROM products WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
echo "Product deleted successfully";
// Displaying products with delete links
$result = $conn->query("SELECT * FROM products");
while ($row = $result->fetch_assoc()) {
echo $row['id'] . " - " . $row['name'] . " - " . $row['price'] . " ";
echo "<a href='?delete=" . $row['id'] . "'>Delete</a><br>";
?>
```
### Summary
- **Working with Dates and Time**: Use `date()`, `DateTime`, and related
functions for date and time manipulation.
- **Pagination**: Divide large datasets into smaller chunks using limit and
offset in SQL queries.
- **CRUD Application**: Create, read, update, and delete records in a database
using PHP and SQL.
These topics cover essential functionalities for developing dynamic and
interactive web applications with PHP.
Let's cover each of these topics: creating a user authentication system, an
introduction to Ajax, an introduction to PHP libraries, an introduction to PHP
frameworks with a focus on Laravel, and finally, a demonstration of hosting an
application.
Creating a User Authentication System
A user authentication system is essential for many web applications. It typically
involves registering users, logging them in, and securing certain parts of the
application.
#### Steps to Create a User Authentication System
1. **Database Structure**:
```sql
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
2. **User Registration**:
```php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$stmt = $conn->prepare("INSERT INTO users (username, password)
VALUES (?, ?)");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->close();
echo "User registered successfully";
}
?>
<form method="post">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Register">
</form>
```
3. **User Login**:
```php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
if ($user && password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
echo "Login successful";
} else {
echo "Invalid username or password";
$stmt->close();
?>
<form method="post">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Login">
</form>
```
4. **User Logout**:
```php
<?php
session_start();
session_unset();
session_destroy();
echo "Logged out successfully";
?>
```
5. **Protecting Pages**:
```php
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
// Protected content here
?>
```
### Introduction to Ajax
Ajax (Asynchronous JavaScript and XML) allows you to send and receive data
asynchronously without reloading the web page. This creates a smoother and
more interactive user experience.
#### Example: Fetching Data with Ajax
1. **HTML and JavaScript**:
```html
<!DOCTYPE html>
<html>
<body>
<button onclick="loadData()">Load Data</button>
<div id="result"></div>
<script>
function loadData() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("result").innerHTML = xhr.responseText;
};
xhr.send();
</script>
</body>
</html>
```
2. **PHP (data.php)**:
```php
<?php
echo "This is the data fetched via Ajax.";
?>
```
### Introduction to PHP Library
PHP libraries are collections of pre-written code that help you solve common
problems without reinventing the wheel. They can be installed and managed
using Composer, PHP's dependency manager.
#### Example: Using the Guzzle HTTP Client Library
1. **Install Composer**: [Download and Install
Composer](https://getcomposer.org/download/)
2. **Install Guzzle**:
```bash
composer require guzzlehttp/guzzle
```
3. **Using Guzzle**:
```php
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('GET',
'https://api.github.com/repos/guzzle/guzzle');
echo $response->getBody();
?>
```
### Introduction to PHP Framework (Laravel)
Laravel is a popular PHP framework that simplifies many common tasks in web
development, such as routing, authentication, and database interactions.
#### Getting Started with Laravel
1. **Install Laravel via Composer**:
```bash
composer global require laravel/installer
laravel new myproject
cd myproject
```
2. **Setting Up the Environment**:
- Create a `.env` file for environment configuration. Update database
settings accordingly.
- Run migrations to set up the database:
```bash
php artisan migrate
```
3. **Basic Routing and Controllers**:
- Define a route in `routes/web.php`:
```php
Route::get('/', function () {
return view('welcome');
});
```
- Create a controller:
```bash
php artisan make:controller UserController
```
- Define a method in the controller:
```php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
public function index()
$users = User::all();
return view('users.index', compact('users'));
```
- Create a view (`resources/views/users/index.blade.php`):
```html
<!DOCTYPE html>
<html>
<head>
<title>Users</title>
</head>
<body>
<h1>Users List</h1>
<ul>
@foreach ($users as $user)
<li>{{ $user->name }}</li>
@endforeach
</ul>
</body>
</html>
```
### Demonstration with Hosting of Our Application
To demonstrate the complete process, we'll consider deploying a Laravel
application on a platform like Heroku.
#### Steps to Host a Laravel Application on Heroku
1. **Set Up Heroku CLI**:
- Install the [Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli).
2. **Create a Heroku Application**:
```bash
heroku create my-laravel-app
```
3. **Deploy the Application**:
- Initialize a Git repository if not already done:
```bash
git init
git add .
git commit -m "Initial commit"
```
- Push to Heroku:
```bash
heroku git:remote -a my-laravel-app
git push heroku master
```
4. **Configure Environment Variables**:
- Set environment variables for the database and other configurations:
```bash
heroku config:set APP_KEY=$(php artisan key:generate --show)
heroku config:set DB_CONNECTION=mysql DB_HOST=your-db-host
DB_PORT=3306 DB_DATABASE=your-db-name DB_USERNAME=your-db-
username DB_PASSWORD=your-db-password
```
5. **Run Database Migrations**:
```bash
heroku run php artisan migrate
```
6. **Open the Application**:
```bash
heroku open
```
### Summary
- **User Authentication**: Implement registration, login, and logout
functionality.
- **Ajax**: Use Ajax to fetch data asynchronously without reloading the page.
- **PHP Libraries**: Utilize Composer to manage libraries like Guzzle.
- **Laravel Framework**: Leverage Laravel for streamlined web development.
- **Hosting**: Deploy your application on platforms like Heroku for live access.
These steps provide a comprehensive approach to building, enhancing, and
deploying a web application using PHP and related technologies.