Dive into Web Development with PHP Your Complete Guide

Advanced PHP Techniques Optimizing Performance and Security in Development.

Strat Your Test Now Dear learners, Are you interested in assessing your progress? Request your mentor to give you access and start your Test.

“Explore PHP through comprehensive online courses, covering fundamentals to advanced topics. Gain practical skills in web development, database integration, and dynamic content creation. Learn efficiently with expert instructors.”

Learn PHP Basic

1.  Introduction if PHP  :

  • Understanding what PHP is and its role in web development.

Understanding what PHP is and its role in web development is crucial for anyone diving into web development. PHP, which stands for “Hypertext Preprocessor,” is a server-side scripting language designed for web development. Here are key points to grasp about PHP and its role:

  1. Server-Side Scripting Language:

    • PHP is executed on the server, not on the user’s browser. When a user requests a web page, the server processes the PHP code and sends the output (usually HTML) to the browser.
  2. Dynamic Web Pages:

    • PHP is particularly adept at creating dynamic web pages. It allows developers to embed PHP code directly within HTML, enabling the generation of content that can change based on various conditions.
  3. Embedding PHP in HTML:

    • PHP code is often embedded between <?php and ?> tags within HTML files. This integration allows developers to mix server-side logic with the presentation layer, making it easier to create dynamic and data-driven websites.
  4. Data Processing:

    • PHP is commonly used for processing form data submitted by users. It can validate input, interact with databases, and generate dynamic responses based on user actions.
  5. Database Connectivity:

    • PHP has extensive support for interacting with databases, making it a powerful tool for creating database-driven web applications. Popular databases like MySQL, PostgreSQL, and others can be easily integrated.
  6. Versatility and Platform Independence:

    • PHP is a versatile language that can run on various operating systems (Windows, Linux, macOS) and is compatible with different web servers (Apache, Nginx).
  7. Open Source and Community-Driven:

    • PHP is open-source, meaning its source code is freely available. It has a large and active community that contributes to its development, creating a wealth of resources, frameworks, and libraries.
  8. Server-Side Tasks:

    • Beyond web page generation, PHP can perform various server-side tasks, such as file manipulation, sending emails, and handling authentication.

In summary, PHP is a powerful server-side scripting language primarily used for creating dynamic and interactive web pages. Its versatility and ease of integration with HTML make it a popular choice for web developers.

Setting up a basic PHP development environment.(Xampp,wampp)

Setting up a basic PHP development environment using XAMPP or WampServer (Wamp) is a common and straightforward process. These tools provide an integrated solution that includes the Apache web server, MySQL database, and PHP interpreter. Here are step-by-step instructions for setting up a basic PHP development environment using XAMPP or WampServer:

XAMPP:

  1. Download and Install XAMPP:
    • Visit the XAMPP official website and download the installer for your operating system (Windows, macOS, Linux).
    • Run the installer and follow the on-screen instructions to complete the installation.
  2. Start Apache and MySQL:
    • After installation, launch the XAMPP Control Panel.
    • Start the Apache server and MySQL by clicking on their respective “Start” buttons.
  3. Verify Installation:
    • Open your web browser and navigate to http://localhost. If XAMPP is installed correctly, you should see the XAMPP welcome page.
  4. Create a PHP File:
    • Create a new PHP file (e.g., index.php) in the htdocs directory within the XAMPP installation folder.
    • Add some basic PHP code, for example:
      php
      <?php
      echo "Hello, PHP!";
      ?>
  5. Access the PHP File:
    • Open your web browser and go to http://localhost/yourfile.php, replacing “yourfile.php” with the actual name of your PHP file.
    • You should see the output of your PHP code.

WampServer (Wamp):

  1. Download and Install WampServer:
    • Visit the WampServer official website and download the installer for your Windows version (32-bit or 64-bit).
    • Run the installer and follow the on-screen instructions to complete the installation.
  2. Start WampServer:
    • After installation, launch WampServer from the desktop shortcut or Start menu.
    • The WampServer icon in the system tray should turn green, indicating that the server is running.
  3. Access Localhost:
    • Open your web browser and go to http://localhost.
    • If WampServer is installed correctly, you should see the WampServer homepage.
  4. Create a PHP File:
    • Create a new PHP file (e.g., index.php) in the www directory within the WampServer installation folder.
    • Add some basic PHP code, similar to the XAMPP example
  5. Access the PHP File:
    • Open your web browser and go to http://localhost/yourfile.php, replacing “yourfile.php” with the actual name of your PHP file.
    • You should see the output of your PHP code.
Now, you have a basic PHP development environment set up with either XAMPP or WampServer. You can continue to build and test your PHP applications in this environment.

2. Basic Syntax and Variables:

  • Learning PHP syntax and how to declare variables.

Learning the PHP syntax and how to declare variables is a fundamental step in getting started with PHP programming. Here’s a brief overview of PHP syntax and examples of declaring variables:

PHP Syntax Basics:

  1. Script Tags:

    • PHP code is enclosed within <?php and ?> tags.
  2. Comments:

    • Single-line comments start with //, and multi-line comments are enclosed between /* and */.

PHP

<?php
// PHP code goes here
?>

 

// This is a single-line comment

/*
This is a
multi-line comment
*/

OUTPUT

Semicolons:

Statements in PHP end with a semicolon (;).

Echo/Print:

To output content, you can use echo or print.

PHP

$variable = "Hello, PHP!"; // Statement ends with a semicolon


echo "Hello, PHP!";
print "Welcome to PHP!";

OUTPUT

Hello, PHP!Welcome to PHP!

Declaring Variables:

  1. Variable Names:

    • Variable names in PHP start with a dollar sign ($) followed by the variable name. They can include letters, numbers, and underscores but must start with a letter or underscore.

PHP

      $myVariable;
$user_name;

OUTPUT

Variable Assignment:

  • Variables are assigned using the = operator.

Data Types:

  • PHP is loosely typed, and variables do not need explicit declarations. They automatically take on the data type of the assigned value.

Concatenation:

  • Concatenate strings using the . operator.

PHP

$message = "Hello, World!";

$integerVar = 42; // Integer
$floatVar = 3.14; // Float (double)
$stringVar = "PHP"; // String
$boolVar = true; // Boolean

$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;


OUTPUT

Exploring data types and basic operators. :

Let’s explore data types and basic operators in programming. I’ll provide an overview using JavaScript as an example language, but these concepts are applicable to various programming languages.

Data Types:

  1. Numeric Data Type:

    • Represents numbers.
    • Example: let age = 25;
  2. String Data Type:

    • Represents sequences of characters.
    • Example: let name = "John";
  3. Boolean Data Type:

    • Represents true or false values.
    • Example: let isStudent = true;
  4. Array:

    • Represents an ordered collection of values.
    • Example: let numbers = [1, 2, 3, 4, 5];
  5. Object:

    • Represents a collection of key-value pairs.
  6. Undefined:

    • Represents a variable that has been declared but not assigned.
    • Example: let x; // undefined
  7. Null:

    • Represents the intentional absence of any object value.
    • Example: let y = null;

PHP

    let person = {
name: "Alice",
age: 30,
isStudent: false
};

OUTPUT

Name: Alice
Age: 30
Is Student: false

Basic Operators:

  1. Arithmetic Operators:

    • + (addition), - (subtraction), * (multiplication), / (division), % (modulo).

PHP

let a = 5;
let b = 2;

let sum = a + b; // 7
let difference = a – b; // 3
let product = a * b; // 10
let quotient = a / b; // 2.5
let remainder = a % b; // 1

OUTPUT

Sum: 7
Difference: 3
Product: 10
Quotient: 2.5
Remainder: 1

Comparison Operators:

  • == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to).

PHP

let x = 5;
let y = 10;

console.log(x == y); // false
console.log(x < y); // true

OUTPUT

 false
true

Logical Operators:

  • && (logical AND), || (logical OR), ! (logical NOT).

PHP

let isStudent = true;
let isEmployed = false;

console.log(isStudent && isEmployed); // false
console.log(isStudent || isEmployed); // true
console.log(!isStudent); // false

 

OUTPUT

false
true
falsexx

Assignment Operators:

  • = (assignment), +=, -=, *=, /=, %=.

Unary Operators:

  • ++ (increment), -- (decrement).

PHP

let a = 5;
a += 3; // equivalent to a = a + 3;

let count = 10;
count++; // increment by 1

OUTPUT

8
11

3.  Control Structures:

  • Conditional statements (if, else, elseif).

In PHP, conditional statements like if, else, and elseif are used to control the flow of the program based on different conditions. Here’s an overview of how these statements are structured:

  • If the temperature is greater than 30, it will output “It’s hot outside.”
  • If the temperature is between 20 and 30 (inclusive), it will output “It’s warm outside.”
  • If the temperature is 20 or less, it will output “It’s cool outside.”

These conditional statements help you make decisions in your PHP code based on the values of variables or the results of expressions.

if Statement:

The basic if statement allows you to execute a block of code if a specified condition is true.

PHP

<?php
$temperature = 25;

if ($temperature > 30) {
echo “It’s hot outside.”;
}
?>

OUTPUT

"It's hot outside."

ifelse Statement:

The ifelse statement allows you to execute one block of code if the condition is true and another block if the condition is false.

PHP

     <?php
$temperature = 25;

if ($temperature > 30) {
echo “It’s hot outside.”;
} else {
echo “It’s not too hot.”;
}
?>

OUTPUT

It's not too hot.

ifelseifelse Statement:

The ifelseifelse statement allows you to test multiple conditions in sequence.

PHP

 30) {
    echo "It's hot outside.";
} elseif ($temperature > 20) {
    echo "It's warm outside.";
} else {
    echo "It's cool outside.";
}
?>

OUTPUT

It's warm outside.
Loops (for, while, do-while) for repetitive tasks:
In PHP, loops are used to execute a block of code repeatedly. The three main types of loops are for, while, and do-while. Here’s an overview of each:
for Loop:
The for loop is used when you know in advance how many times the loop should run.

PHP

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

OUTPUT

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
while Loop:
The while loop is used when the number of iterations is not known in advance, and the loop continues as long as a specified condition is true.

PHP

<?php
$count = 1;

while ($count <= 5) {
echo “Iteration $count<br>”;
$count++;
}
?>

OUTPUT

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
do-while Loop:

The do-while loop is similar to the while loop, but it always executes the block of code at least once before checking the condition.

Loops are essential for handling repetitive tasks, and the choice between for, while, or do-while depends on the specific requirements of your code.

PHP

<?php
$count = 1;

do {
echo “Iteration $count<br>”;
$count++;
} while ($count <= 5);
?>

OUTPUT

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

Arrays :

  • Creating and manipulating arrays

In PHP, arrays are used to store multiple values under a single variable name. Here’s an overview of creating and manipulating arrays in PHP:

Creating Arrays:

Numeric Array:

PHP

<?php
// Numeric Array
$numbers = array(1, 2, 3, 4, 5);
// Alternatively: $numbers = [1, 2, 3, 4, 5];
?>

OUTPUT

Using print_r:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )

Using var_dump:
array(5) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) }bnbb

Associative Array:

PHP

<?php
// Associative Array
$person = array(
"name" => "John",
"age" => 30,
"isStudent" => false
);
// Alternatively: $person = ["name" => "John", "age" => 30, "isStudent" => false];
?>

<?php // Multidimensional Array $students = array( array("name" => "Alice", "age" => 25), array("name" => "Bob", "age" => 22) ); ?>

OUTPUT

Name: John 
Age: 30
Is Student: No

Array
(
[0] => Array
(
[name] => Alice
[age] => 25
)

[1] => Array
(
[name] => Bob
[age] => 22
)

)

 

Accessing Array Elements:

PHP

<?php
echo $numbers[2]; // Accessing the third element of the $numbers array (index starts from 0)
echo $person["name"]; // Accessing the "name" element of the $person array
echo $students[0]["name"]; // Accessing the "name" element of the first element in the $students array
?>

OUTPUT

Modifying Array Elements:

PHP

<?php
$numbers[1] = 10; // Modifying the second element of the $numbers array
$person["age"] = 35; // Modifying the "age" element of the $person array
$students[1]["age"] = 23; // Modifying the "age" element of the second element in the $students array
$students[] = $newStudent; // Adding a new element to the end of the $students array
?>

OUTPUT

Iterating Through an Array:

Using foreach:

These examples cover the basics of creating, accessing, modifying, and iterating through arrays in PHP. Arrays are versatile and are commonly used for various data storage and manipulation tasks in PHP applications.

PHP

<?php
foreach ($numbers as $value) {
echo $value . "<br>";
}
// Similarly, you can use foreach for associative arrays and multidimensional arrays.
?>

OUTPUT

  • Understanding associative arrays
In PHP, an associative array is a type of array where each element is identified by a unique key, rather than by a numeric index. This allows you to create relationships between keys and values. Here’s an overview of associative arrays in PHP:
Creating Associative Arrays:
Associative arrays are created using the array() construct or the shorthand square bracket syntax ([]).

PHP

<?php
// Using array() construct
$person = array(
“name” => “John”,
“age” => 30,
“isStudent” => false
);

// Using square bracket syntax
$address = [
“street” => “123 Main St”,
“city” => “Anytown”,
“zip” => “12345”
];
?>

OUTPUT

Person:
Array
(
[name] => John
[age] => 30
[isStudent] => false
)

Address:
Array
(
[street] => 123 Main St
[city] => Anytown
[zip] => 12345
)

Accessing Values in Associative Arrays:

Values in associative arrays are accessed using their corresponding keys

PHP

        <?php
echo $person["name"]; // Outputs: John
echo $person["age"]; // Outputs: 30
echo $address["city"]; // Outputs: Anytown

OUTPUT

John
30
Anytown

Modifying Values in Associative Arrays:

You can modify values in associative arrays by referencing the key.

PHP

    <?php
$person["age"] = 35; // Modifying the value associated with the "age" key
$address["zip"] = "54321"; // Modifying the value associated with the "zip" key

OUTPUT

Adding New Key-Value Pairs:

To add new key-value pairs, simply assign a value to a new key.

PHP

   <?php
$person["gender"] = "male"; // Adding a new key-value pair
$address["state"] = "CA"; // Adding a new key-value pair

OUTPUT

Iterating Through Associative Arrays:

You can use foreach to iterate through all key-value pairs in an associative array.

<?php
foreach ($person as $key => $value) {
echo “$key: $value<br>”;
}

PHP

   

OUTPUT

name: John
age: 35
isStudent: false
gender: male
Functions   :
  • Defining and using functions
In PHP, functions are blocks of reusable code that perform a specific task. They allow you to organize code into logical units, making it easier to maintain and reuse. Here’s an overview of defining and using functions in PHP:

Defining Functions:

You can define a function using the function keyword, followed by the function name, parameters (if any), and the code block enclosed in curly braces {}.

PHP

<?php
// Function without parameters
function greet() {
echo “Hello, world!”;
}

// Function with parameters
function add($a, $b) {
return $a + $b;
}
?>

OUTPUT

Hello, world!
The sum is: 8

Calling Functions:

You can call a function by using its name followed by parentheses (). If the function has parameters, you need to pass the appropriate arguments within the parentheses.

PHP

<?php
// Calling the greet() function
greet();

// Calling the add() function with arguments
$result = add(5, 3);
echo “The sum is: $result”;
?>

OUTPUT

Hello, world!The sum is: 8

Returning Values:

Functions can return values using the return statement. This allows you to capture the result of a function and use it elsewhere in your code.

PHP

<?php
function add($a, $b) {
return $a + $b;
}

$result = add(5, 3);
echo “The sum is: $result”; // Outputs: The sum is: 8
?>

OUTPUT

The sum is :8

Default Parameter Values:

You can specify default values for parameters in a function. If a value is not provided for a parameter when the function is called, the default value will be used.

PHP

<?php
function greet($name = “World”) {
echo “Hello, $name!”;
}

greet(); // Outputs: Hello, World!
greet(“Alice”); // Outputs: Hello, Alice!
?>

OUTPUT

Hello, World!

Hello, Alice!

  • Variable Scope:

    Variables declared inside a function have local scope by default, meaning they are only accessible within that function. Variables declared outside of any function have global scope, meaning they are accessible anywhere in the script. values.

PHP

<?php
$globalVar = “I’m global”;

function testScope() {
$localVar = “I’m local”;
echo $globalVar; // Accessible (prints “I’m global”)
echo $localVar; // Accessible (prints “I’m local”)
}

testScope();
echo $localVar; // Not accessible (generates an error)
?>

OUTPUT

I'm global
I'm local
b. Scope of variables within functions.:
  • In PHP, the scope of a variable refers to the context in which the variable is defined and can be accessed. Variables can have different scopes depending on where they are declared, and this affects where they can be used within a PHP script. Here’s an overview of variable scope within functions in PHP:

    Local Scope:

    Variables declared inside a function are considered to have local scope. This means they are accessible only within the function where they are declared.

PHP

<?php
function testScope() {
$localVar = “I’m local”;
echo $localVar; // Accessible (prints “I’m local”)
}

testScope(); // Call the function
echo $localVar; // Not accessible (generates an error)
?>

OUTPUT

I'm local

Global Scope:

Variables declared outside of any function, at the top level of a PHP script, have global scope. This means they can be accessed from anywhere in the script, including inside functions.

PHP

<?php
$globalVar = "I'm global";

function testScope() {
global $globalVar; // Access the global variable within the function
echo $globalVar; // Accessible (prints “I’m global”)
}

testScope(); // Call the function
echo $globalVar; // Accessible (prints “I’m global”)
?>

OUTPUT

I'm global
I'm global

Static Variables:

Variables declared as static within a function retain their value between function calls. They are initialized only once and their value persists throughout the execution of the script.jmnjnnn

PHP

<?php
function increment() {
static $counter = 0;
$counter++;
echo $counter . “<br>”;
}

increment(); // Outputs: 1
increment(); // Outputs: 2
increment(); // Outputs: 3
?>

OUTPUT

1
2
3
6. Forms and User input:
a. Handling form data using PHP.(including ajax):
  • Handling form data using PHP involves receiving form submissions from HTML forms, processing the submitted data, and taking appropriate actions based on the received data. AJAX (Asynchronous JavaScript and XML) can be used to submit form data asynchronously without refreshing the entire web page. Here’s an overview of handling form data using PHP, including AJAX:

    HTML Form:

    First, you need to create an HTML form that collects user input.

HTML

<!-- HTML Form -->
<form id="myForm" action="process.php" method="post">
<input type="text" name="username" placeholder="Enter username">
<input type="password" name="password" placeholder="Enter password">
<button type="submit">Submit</button>
</form>

OUTPUT

 ["grape", "banana", "orange"]

  [2, 3, 4]

  [“apple”, “grape”, “kiwi”, “banana”]

PHP Processing (process.php):

Create a PHP script to handle form submissions.

AJAX Submission (JavaScript):

Use JavaScript to send form data asynchronously using AJAX.

Handling Form Data in PHP:

  • Use $_POST superglobal to access form data submitted using the POST method.
  • Use $_GET superglobal to access form data submitted using the GET method.
  • Use $_REQUEST superglobal to access form data submitted using either POST or GET methods.

PHP

<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form data
$username = $_POST["username"];
$password = $_POST["password"];
// Perform validation or processing
// For example, you can check credentials, save data to a database, etc.

// Send response
echo "Form submitted successfully!";
} else {
// If form is not submitted, return error
echo "Error: Form not submitted!";
}
?>

JS

// JavaScript (using jQuery)
$(document).ready(function() {
$(“#myForm”).submit(function(event) {
// Prevent default form submission
event.preventDefault();

// Serialize form data
var formData = $(this).serialize();

// Send AJAX request
$.ajax({
type: “POST”,
url: “process.php”,
data: formData,
success: function(response) {
// Handle successful response
alert(response);
},
error: function(xhr, status, error) {
// Handle error
console.error(xhr.responseText);
}
});
});
});

Basic form validation

Basic form validation in PHP involves checking that the required form fields are not empty and may include additional checks such as validating email addresses, ensuring numeric values are provided for numeric fields, etc. Here’s an example of how to perform basic form validation in PHP:

HTML

<!-- HTML Form -->
<form action="process.php" method="post">
<input type="text" name="username" placeholder="Enter username">
<input type="email" name="email" placeholder="Enter email">
<input type="password" name="password" placeholder="Enter password">
<button type="submit">Submit</button>
</form>

JS

<?php
// Check if the form is submitted
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
// Initialize an array to store validation errors
$errors = [];

// Validate username
if (empty($_POST[“username”])) {
$errors[] = “Username is required”;
}

// Validate email
if (empty($_POST[“email”])) {
$errors[] = “Email is required”;
} elseif (!filter_var($_POST[“email”], FILTER_VALIDATE_EMAIL)) {
$errors[] = “Invalid email format”;
}

// Validate password
if (empty($_POST[“password”])) {
$errors[] = “Password is required”;
}

// If there are no validation errors, proceed with processing the form data
if (empty($errors)) {
// Process form data, perform database operations, etc.

// Send response
echo “Form submitted successfully!”;
} else {
// If there are validation errors, output them
foreach ($errors as $error) {
echo $error . “<br>”;
}
}
} else {
// If form is not submitted, return error
echo “Error: Form not submitted!”;
}
?>

7. Working with Strings:
a. String manipulation and functions.:
  • String manipulation in PHP involves performing various operations on strings such as concatenation, splitting, searching, replacing, and formatting. PHP provides a rich set of built-in functions to manipulate strings efficiently. Here’s an overview of some common string manipulation functions in PHP:

    Concatenation:

PHP

$string1 = "Hello";
$string2 = "World";
$result = $string1 . " " . $string2; // Concatenation using the . operator
echo $result; // Outputs: Hello World

OUTPUT

Hello World
b. String Length:
c. Substring:

HTML

$string = "Hello World";
$length = strlen($string); // Get the length of the string
echo $length; // Outputs: 11

$string = "Hello World";
$substring = substr($string, 6); // Get substring starting from index 6
echo $substring; // Outputs: World

OUTPUT

11
World
a. Uppercase and Lowercase:
b. Searching and Replacing:

PHP

$string = "Hello World";
$uppercase = strtoupper($string); // Convert to uppercase
$lowercase = strtolower($string); // Convert to lowercase
echo $uppercase; // Outputs: HELLO WORLD
echo $lowercase; // Outputs: hello world

PHP

$string = "Hello World";
$uppercase = strtoupper($string); // Convert to uppercase
$lowercase = strtolower($string); // Convert to lowercase
echo $uppercase; // Outputs: HELLO WORLD
echo $lowercase; // Outputs: hello world
C. Trimming and Padding:
D. Formatting:

PHP

$string = " Hello World ";
$trimmedString = trim($string); // Remove leading and trailing whitespace
$paddedString = str_pad($string, 20, "*"); // Pad the string to a length of 20 with "*"
echo $trimmedString; // Outputs: Hello World
echo $paddedString; // Outputs: ***Hello World*****

PHP

$string = "hello world";
$ucFirst = ucfirst($string); // Uppercase the first character
$ucWords = ucwords($string); // Uppercase the first character of each word
echo $ucFirst; // Outputs: Hello world
echo $ucWords; // Outputs: Hello World
Regular expressions for pattern matching.
Regular expressions (regex) in PHP are powerful tools for pattern matching and manipulation of strings. They allow you to search for patterns within strings, validate input, and perform various text processing tasks. Here’s an overview of regular expressions in PHP:

Basic Pattern Matching:

Metacharacters:
  • . : Matches any single character except newline.
  • ^ : Matches the start of the string.
  • $ : Matches the end of the string.
  • [] : Matches any single character within the brackets.
  • | : Acts like an OR operator.
  • () : Groups expressions together.
Quantifiers:
  • * : Matches zero or more occurrences.
  • + : Matches one or more occurrences.
  • ? : Matches zero or one occurrence.
  • {n} : Matches exactly n occurrences.
  • {n,} : Matches n or more occurrences.
  • {n,m} : Matches at least n and at most m occurrences.
Character Classes:
  • \d : Matches any digit character.
  • \D : Matches any non-digit character.
  • \w : Matches any word character (alphanumeric plus underscore).
  • \W : Matches any non-word character.
  • \s : Matches any whitespace character.
  • \S : Matches any non-whitespace character.
Anchors:
  • ^ : Matches the start of the string.
  • $ : Matches the end of the string.
  • \b : Matches a word boundary.

Regex Functions in PHP:

  • preg_match() : Performs a regex match against a string.
  • preg_match_all() : Performs a global regex match against a string.
  • preg_replace() : Performs a regex search and replace on a string.
  • preg_split() : Splits a string by a regex pattern.

PHP

$string = "The quick brown fox jumps over the lazy dog";
if (preg_match("/\bfox\b/", $string)) {
echo "Pattern found!";
} else {
echo "Pattern not found!";
}

PHP

$string = "hello world";
$ucFirst = ucfirst($string); // Uppercase the first character
$ucWords = ucwords($string); // Uppercase the first character of each word
echo $ucFirst; // Outputs: Hello world
echo $ucWords; // Outputs: Hello World

8.  Introduction to Databases:

Connecting to databases (MySQL, for example)

  • To connect to a MySQL database from a PHP script, you can use the MySQLi (MySQL Improved) extension or PDO (PHP Data Objects). Here’s how to connect using both methods:

Using MySQLi Extension:

<?php
// Database credentials
$host = "localhost";
$username = "username";
$password = "password";
$database = "dbname";

// Create a connection
$conn = new mysqli($host, $username, $password, $database);

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

echo "Connected successfully";
?>

Using PDO:

<?php
// Database credentials
$host = “localhost”;
$username = “username”;
$password = “password”;
$database = “dbname”;

try {
// Create a connection
$conn = new PDO(“mysql:host=$host;dbname=$database”, $username, $password);
// Set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo “Connected successfully”;
} catch(PDOException $e) {
echo “Connection failed: ” . $e->getMessage();
}
?>

Executing Queries:

You can execute SQL queries using either method:

Using MySQLi:

$sql = "SELECT * FROM tablename";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data
} else {
    echo "0 results";
}

Using PDO:

$sql = "SELECT * FROM tablename";
$stmt = $conn->query($sql);

while ($row = $stmt->fetch()) {
    // Output data
}
Basic CRUD operations (Create, Read, Update, Delete):
Below is an example of basic CRUD operations (Create, Read, Update, Delete) using PHP and MySQLi extension. This example assumes you have a MySQL database named example with a table named users having columns id, username, and email.
Create (INSERT):

PHP

<?php
// Database connection
$host = "localhost";
$username = "username";
$password = "password";
$database = "example";

$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Insert data
$username = "John";
$email = "john@example.com";

$sql = "INSERT INTO users (username, email) VALUES ('$username', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

OUTPUT

Read (SELECT):

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

// Read data
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"] . " - Name: " . $row["username"] . " - Email: " . $row["email"] . "
"; } } else { echo "0 results"; } $conn->close(); ?>

OUTPUT

Update (UPDATE):

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

// Update data
$id = 1;
$newUsername = "UpdatedName";

$sql = "UPDATE users SET username='$newUsername' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

OUTPUT

Delete (DELETE):

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

// Delete data
$id = 1;

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

$conn->close();
?>

OUTPUT

Dear learners, Are you interested in assessing your progress?
Request your mentor to give you access and start your Test.