UNIT 5: PHP

 

UNIT 5: PHP

PHP (Hypertext Preprocessor) is a widely-used open-source scripting language that is especially suited for web development. It can be embedded into HTML and is used for server-side scripting to create dynamic web pages. In this unit, we will explore various aspects of PHP, including server-side scripting, arrays, functions, advanced PHP topics, database operations, and working with phpMyAdmin.


5.1. Server-Side Scripting

Server-side scripting refers to scripts that run on the server rather than the client-side. When a user requests a page, the server processes the request, executes the script, and returns the generated content to the user's browser. PHP is used for server-side scripting to generate dynamic web pages based on user interactions.

5.1.1. Arrays in PHP

An array in PHP is a data structure that stores multiple values in a single variable. Arrays are useful for storing a collection of similar data types, such as numbers or strings.

Types of Arrays in PHP:
  1. Indexed Arrays: Arrays where each element is accessed via an index (numeric index).
  2. Associative Arrays: Arrays where each element is accessed via a key (string).
  3. Multidimensional Arrays: Arrays that contain other arrays.
Example of Indexed Array:
$fruits = array("Apple", "Banana", "Cherry"); echo $fruits[0]; // Output: Apple
Example of Associative Array:
$person = array("name" => "John", "age" => 25); echo $person["name"]; // Output: John
Example of Multidimensional Array:
$contacts = array( array("John", "john@example.com"), array("Jane", "jane@example.com") ); echo $contacts[0][0]; // Output: John

5.1.2. Functions and Forms

Functions in PHP are blocks of code designed to perform a particular task. Functions are reusable, which makes your code more organized and efficient.

Creating a Function:
function greet($name) { return "Hello, " . $name; } echo greet("Alice"); // Output: Hello, Alice
Handling Forms in PHP:

Forms are often used to collect data from users. PHP can handle form data by using the $_GET or $_POST methods.

  • GET method is used for form data that is appended to the URL.
  • POST method is used for form data that is not visible in the URL and is more secure.
Example of Handling Form Data:

<form method="post" action="process.php"> Name: <input type="text" name="name"> <input type="submit" value="Submit"> </form>

// process.php $name = $_POST['name']; echo "Hello, " . $name;

5.1.3. Advanced PHP

Advanced PHP includes more complex topics such as:

  1. Object-Oriented Programming (OOP): Using classes and objects in PHP.
  2. Sessions and Cookies: Maintaining state between web pages.
  3. Error Handling: Managing errors using try-catch blocks.
  4. File Handling: Uploading, reading, writing, and deleting files on the server.

Example of OOP in PHP:

class Person { public $name; public $age; function __construct($name, $age) { $this->name = $name; $this->age = $age; } function greet() { return "Hello, " . $this->name; } } $person1 = new Person("Alice", 25); echo $person1->greet(); // Output: Hello, Alice

5.2. Databases

PHP is commonly used in conjunction with databases like MySQL to store and retrieve data dynamically. The interaction with databases is done using SQL queries.

5.2.1. Basic Command with PHP Examples

PHP and MySQL commands are used to connect to the database, execute queries, and retrieve data. The mysqli (MySQL improved) extension is commonly used for these operations.

Example of Connecting to MySQL:

$conn = new mysqli("localhost", "username", "password", "database_name"); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully";

5.2.2. Connection to Server, Creating a Database

To connect to a MySQL database and create a new database:

$conn = new mysqli("localhost", "username", "password"); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Create database $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) { echo "Database created successfully"; } else { echo "Error creating database: " . $conn->error; }

5.2.3. Selecting a Database

To select a database after connecting to the server:

$conn = new mysqli("localhost", "username", "password", "myDB"); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected to the database!";

5.2.4. Listing Databases

To list all the databases in the MySQL server:

$result = $conn->query("SHOW DATABASES"); while ($row = $result->fetch_assoc()) { echo $row['Database'] . "<br>"; }

5.2.5. Listing Table Names, Creating a Table

To list all tables in the selected database:

$result = $conn->query("SHOW TABLES"); while ($row = $result->fetch_assoc()) { echo $row['Tables_in_myDB'] . "<br>"; }

Creating a Table:

$sql = "CREATE TABLE Users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, email VARCHAR(50) )"; if ($conn->query($sql) === TRUE) { echo "Table created successfully"; } else { echo "Error creating table: " . $conn->error; }

5.2.6. Inserting Data

To insert data into a table:

$sql = "INSERT INTO Users (name, email) VALUES ('John', 'john@example.com')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; }

5.2.7. Altering Tables, Queries, Deleting Database, Deleting Data and Tables

Altering a Table:

$sql = "ALTER TABLE Users ADD COLUMN age INT"; if ($conn->query($sql) === TRUE) { echo "Table altered successfully"; } else { echo "Error: " . $conn->error; }

Deleting Data:

$sql = "DELETE FROM Users WHERE id=1"; if ($conn->query($sql) === TRUE) { echo "Record deleted successfully"; } else { echo "Error: " . $conn->error; }

Dropping a Table:

$sql = "DROP TABLE Users"; if ($conn->query($sql) === TRUE) { echo "Table dropped successfully"; } else { echo "Error: " . $conn->error; }

Dropping a Database:

$sql = "DROP DATABASE myDB"; if ($conn->query($sql) === TRUE) { echo "Database dropped successfully"; } else { echo "Error: " . $conn->error; }

5.3. phpMyAdmin and Database Bugs

phpMyAdmin is a web-based interface for managing MySQL databases. It allows users to easily manage databases, tables, and SQL queries via a graphical user interface.

Some common database bugs or issues in PHP and MySQL include:

  • Connection Issues: Incorrect login credentials or server down.
  • SQL Injection: Unescaped input leading to security vulnerabilities.
  • Query Errors: Syntax or logic errors in SQL queries.
  • Data Integrity Issues: Incorrect or duplicate data due to improper handling.

Example of SQL Injection Prevention:

$stmt = $conn->prepare("SELECT * FROM Users WHERE name = ?"); $stmt->bind_param("s", $name); $name = $_POST['name']; $stmt->execute();

Summary

In this unit, we covered key topics related to PHP including:

  1. Server-side scripting: Understanding how PHP works on the server to create dynamic web pages.
  2. Arrays: Using different types of arrays (indexed, associative, multidimensional) in PHP.
  3. Functions and Forms: Creating reusable functions and handling user input through forms.
  4. Advanced PHP: Exploring advanced topics such as Object-Oriented Programming, error handling, and file management.
  5. Databases: Connecting to databases, creating tables, inserting data, and performing CRUD operations.
  6. phpMyAdmin: Using phpMyAdmin to manage MySQL databases and fix common database-related issues.

This knowledge will help you in building dynamic websites that interact with databases to store, retrieve, and manage data.

Post a Comment

0 Comments