Unit III Full Stack
Unit III Full Stack
Introduction to PHP. -Expressions and Control Flow in PHP. -PHP Functions and
Objects-PHP Arrays- GET, POST variables- Embedding PHP- PHP and MySQL
Practice:
2. Write a PHP script to remove comma(s) from the following numeric string
Introduction to PHP
PHP stands for Hypertext Preprocessor. It is an open-source, widely used language for web
development. Developers can create dynamic and interactive websites by embedding PHP code
into HTML. PHP can handle data processing, session management, form handling, and
database integration. The latest version of PHP is PHP 8.4.8, released on June 5, 2025.
• A server-side language that generates dynamic content and interacts with databases,
forms, and sessions.
• Supports easy interaction with databases like MySQL, enabling efficient data handling.
• Runs on multiple operating systems and works with popular web servers like Apache
and Nginx.
Example:
<?php
?>
Output:
Hello, World!
• The user enters a URL into a web browser or clicks on a link, making an HTTP request
to the web server.
• The web server (Apache, Nginx, etc.) receives the HTTP request. The request is
directed to PHP for processing.
• The PHP script processes any server-side logic, such as handling form submissions,
processing data, or making requests to a database.
• If the PHP script requires database interaction, an SQL query is sent to the database.
• The PHP script sends a request to the database (e.g., MySQL) with an SQL query.
• The database processes the query and sends a response (results of the query) back to
the PHP script.
• The web browser receives the HTTP response, which includes dynamic content
generated by PHP.
This is how the PHP workflow operates in web applications, where PHP interacts with a
database and a web server to generate dynamic content for the user.
• A PHP file containing PHP code which is used to create dynamic web pages.
• It Runs on a web server with PHP installed (e.g., Apache, Nginx) and the output is sent
to the browser as plain HTML.
• Generate Dynamic Content: PHP creates dynamic web pages based on user input.
• Manage Files: PHP can create, open, read, write, and delete files on the server.
• Process Form Data: PHP collects and processes data from web forms.
• Handle Cookies: PHP can send and receive cookies to manage sessions.
• Interact with Databases: PHP adds, deletes, and modifies data in databases.
• Control User Access: PHP can manage login systems and user permissions.
• Widely Used: PHP runs on more than 77% of websites, including popular sites like
WordPress and Facebook.
• Cross-Platform: Works on Windows, Linux, and macOS.
• Integrates Easily: Works well with HTML and JavaScript to build dynamic websites.
PHP is considered a loosely typed language, meaning you do not need to specify the data type
when declaring a variable. PHP will automatically interpret the variable’s type based on the
value assigned to it at runtime.
• This allows developers to define the expected data type for function parameters.
• By enabling strict typing, PHP will raise a "Fatal Error" if the passed argument does
not match the declared type.
• PHP dynamically assigns a data type to a variable based on the value it holds. Since the
language is not strongly typed, operations like adding a string to an integer can be
performed without causing an error.
• Client-Side Scripting: PHP can generate dynamic HTML that is sent to the browser.
While it runs on the server, the content it generates can be displayed in the client’s
browser.
• Simple Learning Curve: PHP’s syntax is easy to learn, especially for those with basic
knowledge of HTML and programming concepts.
• Rich Ecosystem: PHP offers many libraries and frameworks like Laravel and Symfony,
which make development faster and more efficient.
• Scalability: PHP is highly scalable, allowing developers to create websites that can
grow in terms of traffic and functionality.
• Asynchronous Support: PHP, through the use of libraries and frameworks like
ReactPHP, supports asynchronous programming, allowing developers to handle
multiple requests concurrently.
Applications of PHP
• Web Development: PHP is widely used for creating dynamic websites and web
applications by generating interactive content, handling user inputs, and interacting
with databases.
• Real-Time Applications: PHP supports real-time applications like chat systems and live
updates, typically using AJAX or WebSockets.
• File Management: PHP handles file uploads and creates file management systems for
organizing and downloading files.
Limitations of PHP
• Security Risks: If not used properly, PHP can be vulnerable to attacks like SQL
injection, XSS, and CSRF. Developers must follow security best practices.
• Not Ideal for Command-Line: While PHP can be run from the command line, it’s
mainly designed
• for web development, so its performance for general-purpose tasks may not be as
efficient as other languages.
• Limited Support for Multi-threading: While PHP can handle concurrent requests by
asynchronous frameworks, multi-threaded support is limited compared to languages
like Java or Node.js.
___________________________________________________________________________
Expressions in PHP
y = 3 (|2x| + 4)
TRUE or FALSE?
A basic Boolean value can be either TRUE or FALSE. For example, the expression “20 > 9”
(20 is greater than 9) is TRUE, and the expression “5 == 6” (5 is equal to 6) is FALSE.
Example
<?php
?>
a: [1]
b: []
c: []
d: [1]
<?php // test2.php
?>
Output:
a: [1]
b: []
The simplest form of an expression is a literal, which simply means something that evaluates
to itself, such as the number 73 or the string “Hello”. An expression could also simply be a
variable, which evaluates to the value that has been assigned to it. They are both types of
expressions because they return a value.
<?php
$myname = "Brian";
$myage = 37;
?>
Output:
a: 73
b: Hello
c:
d: Brian
e: 37
<?php
?>
Control flow statements are used in programming to control the flow of code execution. In
PHP, there are several types of control flow statements, including if-else statement, switch
statement, for loop, while loop, and do-while loop. In this article, we’ll go over each of these
statements and provide examples to help you understand their usage.
If-else statement
If-else statements are used to execute different code based on different conditions. Here is the
syntax for an if-else statement:
if (condition) {
} else {
if (condition1) {
} else {
Example:
<?php
$num = 10;
if ($num < 5) {
} elseif ($num == 5) {
} else {
?>
Output:
SWITCH STATEMENT
Switch statements are used to execute different code based on different values. Here is the
syntax for a switch statement: switch (expression) {
case value1:
break;
case value2:
// code to be executed if expression is equal to value2
break;
default:
In a switch statement, the expression is evaluated and compared to each case value. If the
expression is equal to a case value, the code inside the corresponding set of curly braces is
executed. If the expression is not equal to any of the case values, the code inside the default set
of curly braces is executed.
Example:
<?php
$dayOfWeek = 'Tuesday';
switch ($dayOfWeek) {
case 'Monday':
break;
case 'Tuesday':
break;
case 'Wednesday':
break;
case 'Thursday':
break;
case 'Friday':
break;
default:
?>
Output:
Today is Tuesday
FOR LOOP
For loops are used to repeat a block of code a specific number of times. Here is the syntax for
a for loop:
// code to be executed
In a for loop, the initialization sets the starting point, the condition determines when to stop,
and the increment increases the counter. The code inside the curly braces is executed each time
the loop runs.
Example:
<?php
?>
Output:
1 2 3 4 5 6 7 8 9 10
continue and break are flow control statements used in loops to alter the normal control flow
of the program.
The continue statement is used to skip the current iteration of a loop and continue to the next
iteration. This is useful when you want to skip processing certain items in a loop based on a
specific condition.
On the other hand, the break statement is used to immediately terminate the current loop and
continue with the rest of the program outside the loop. This is useful when you want to exit a
loop prematurely based on a specific condition.
Both continue and break can be used in for, while, and do-while loops to alter the normal flow
of control.
Example:
<?php
if ($i == 3) {
continue;
if ($i == 5) {
break;
echo $i . "<br>";
?>
Output:
1
2
WHILE LOOP
While loops are used to repeat a block of code as long as a condition is true. Here is the syntax
for a while loop:
while (condition) {
// code to be executed
In a while loop, the condition is evaluated at the beginning of each iteration. If the condition is
true, the code inside the curly braces is executed. This continues until the condition becomes
false.
Example:
<?php
$count = 1;
$count++;
?>
Output:
12345
DO-WHILE LOOP
Do-while loops are similar to while loops, but the code inside the curly braces is executed at
least once, even if the condition is false. Here is the syntax for a do-while loop:
do {
// code to be executed
} while (condition);
In a do-while loop, the code inside the curly braces is executed first, and then the condition is
evaluated. If the condition is true, the loop continues to run. If the condition is false, the loop
ends.
Example:
<?php
$count = 1;
do {
$count++;
?>
Output:
12345
PHP Functions:
A function in PHP is a self-contained block of code that performs a specific task. It can accept
inputs (parameters), execute a set of statements, and optionally return a value.
• Functions can accept parameters and return values, enabling dynamic behavior based
on inputs.
• PHP supports both built-in functions and user-defined functions, enhancing flexibility
and modularity in code.
Syntax
Once a function is declared, it can be invoked (called) by simply using the function name
followed by parentheses.
<?php
return $a + $b;
?>
Output:
Functions in PHP can return a value using the return statement. The return value can be any
data type such as a string, integer, array, or object. If no return statement is provided, the
function returns null by default.
example:
<?php
return $a * $b;
}
?>
Output
20
PHP supports anonymous functions, also known as closures. These functions do not have a
name and are often used for passing functions as arguments to other functions.
<?php
$greet = function($name) {
};
$greet("GFG");
?>
Output
Hello, GFG!
In this example:
• The function is called with the argument "GFG", and the greeting "Hello, GFG" is
printed.
Recursion in PHP
Recursion is a process in which a function calls itself. It is often used in situations where a task
can be broken down into smaller, similar tasks.
example:
<?php
function factorial($n) {
if ($n == 0) {
return 1;
} else {
echo factorial(5);
?>
Output
120
In this example:
2. Array Functions
Objects in PHP
An object in PHP is an instance of a class. Objects are used to store data (properties) and define
behaviors (methods) that can be used within an application. An object is created using the new
keyword followed by the class name.
Syntax:
Example:
<?php
class Car {
public $brand;
public $model;
public function drive() {
$myCar->drive();
?>
Output:
PHP Array
Arrays are one of the most important data structures in PHP. They allow you to store multiple
values in a single variable. PHP arrays can hold values of different types, such as strings,
numbers, or even other arrays. Understanding how to use arrays in PHP is important for
working with data efficiently.
• PHP offers many built-in array functions for sorting, merging, searching, and more.
• PHP Arrays can store values of different types (e.g., strings, integers, objects, or even
other arrays) in the same array.
• They allow you to store multiple values in a single variable, making it easier to manage
related data.
Types of Arrays in PHP
1. Indexed Arrays
Indexed arrays use numeric indexes starting from 0. These arrays are ideal when you need to
store a list of items where the order matters.
<?php
?>
Output
apple
<?php
?>
2. Associative Arrays
Associative arrays use named keys, which are useful when you want to store data with
meaningful identifiers instead of numeric indexes.
<?php
$person = array("name" => "GFG", "age" => 30, "city" => "New York");
echo $person["name"];
?>
Output
GFG
3. Multidimensional Arrays
Multidimensional arrays are arrays that contain other arrays as elements. These are used to
represent more complex data structures, such as matrices or tables.
<?php
$students = array(
);
echo $students["GFG"]["age"];
?>
Output
22
In PHP 5.4 and later, you can use the shorthand [] syntax to create arrays.
Note: Both methods are valid, but the shorthand syntax is preferred for its simplicity and
readability.
You can access individual elements in an array using their index (for indexed arrays) or key
(for associative arrays).
You can modify an existing element by assigning a new value to a specific index or key.
You can add new elements to an array using the following methods:
• array_push(): Adds elements to the end of an indexed array.
array_pop($fruits);
array_shift($fruits);
Array Functions
PHP provides a wide range of built-in functions to work with arrays. Here are some common
array functions:
• Array Merge: The array_merge() function combines two or more arrays into one.
• Array Search: The in_array() function checks if a specific value exists in an array.
• Array Sort: The sort() function sorts an indexed array in ascending order.
Array Iteration
You can loop through arrays using loops such as foreach or for.
In PHP, superglobals are built-in global arrays that provide access to certain data types, such
as form inputs, session data, and URL parameters. Among the most commonly used
superglobals in web development are $_GET and $_POST. These superglobals are used to
collect data from HTML forms and URLs.
What is $_GET ?
The $_GET superglobal is used to collect form data sent via the GET method. This method
appends data to the URL as query parameters, which are visible to users in the browser’s
address bar. Some of the features of the $_GET are:
• Retrieves data sent to the server as part of the URL query string.
• Useful for retrieving data that is visible to the user, such as search queries or parameters
in a URL.
• Data sent via $_GET is visible in the URL, making it less secure for sensitive
information.
Syntax:
<?php
echo $_GET['username']; // Outputs the value of the 'username' parameter from the URL
?>
Example:
<html>
<body>
<label>username:</label><br>
</form>
</body>
</html>
<?php
?>
Output:
In this example:
• A form asks the user for a username and submits it via the GET method to index.php.
• The form submits the data to the same page (index.php), allowing the same script to
process the data.
• After submission, PHP retrieves and displays the entered username using
$_GET['username'].
• Since the form uses the GET method, the form data (like the username) is appended to
the URL as query parameters (e.g., index.php?username=anjali), making the username
visible in the browser’s URL bar.
What is $_POST?
The $_POST superglobal is used to collect form data sent via the POST method. Unlike GET,
the POST method sends data in the body of the HTTP request, so the data is not visible in the
URL. Some of the features of the $_POST are:
• Retrieves data sent to the server in the body of an HTTP request, typically
from HTML forms submitted using the POST method.
• Suitable for handling sensitive or large amounts of data as it's not visible in the URL.
• More secure than $_GET for handling sensitive information like passwords.
• Accessed using associative array notation, e.g., $_POST['field_name'].
Syntax:
<?php
echo $_POST['username']; // Outputs the value of the 'username' parameter submitted via
POST
?>
Example:
<html>
<body>
<label>username:</label><br>
</form>
</body>
</html>
<?php
?>
Output:
In this example:
• A form asks the user for a username and submits it via the POST method to index.php.
• The form submits the data to the same page (index.php), ensuring the data is processed
on the same script.
• After submission, PHP retrieves and displays the entered username using
$_POST['username'].
• Since the form uses the POST method, the form data is sent in the HTTP request body,
not in the URL, so the username is not visible in the URL bar.
Use $_GET:
• For data like search terms or filter criteria that don't need security.
• Useful when you need to share or bookmark URLs with parameters (e.g., search
queries).
• Typically used for retrieving data without modifying the server (e.g., reading data from
a database).
Use $_POST:
• Sensitive information (e.g., passwords, payment details) since it is not visible in the
URL.
• Use for submitting forms that change server-side data (e.g., registration forms).
$_GET vs $_POST
Both $_GET and $_POST are superglobals in PHP used to collect form data, but they differ in
how and where the data is transmitted.
$_GET $_POST
Data is visible in the URL Data is hidden in the HTTP request body
Not secure (data is visible) More secure, but still requires sanitization
Embed PHP
HTML is a pre-defined front end language code, whereas php is a server-side scripting
language; it is also called an embedded server-side language. Most of the PHP syntax codes
has to be followed with the c, java and Perl script languages. It normally works with other web-
based dynamic script languages, and also performance side, it will be more better compared to
other script languages whereas it is paired with html codes for creating web-based applications
it is a non-interruptible functioning type for creating the websites.
Syntax:
The Embed PHP code is the standard one that is a normal html document; we have written the
PHP code on the html page.
Code:
<html>
<head>
<title>
</title>
<script language="php">
-----some codes----
</script>
</head>
</html>
The above code is the basic syntax for embedding the php code in html page with the help of
<script> tags; it is also another type of style for portable codes.
• In Php code, we also wrote an embedded code inside. It normally looks like an HTML
code it also runs in the normal browsers as the source the raw PHP code is not visible
in the browsers because the interpreter in the PHP has run through the script mode, and
also it will display the output as from the expected script results as the user is given
inputs and getting outputs as test cases.
• This means that the PHP code, which we will already reproduce with the clean html
viewable codes with any type of web browsers, instead the user does not understand
the PHP codes in the browsers. This type of process will come in the server-side
scripting concepts in a nutshell thats why PHP has an interpreted and executed within
the web browsers compatible with any type of user’s local PCs.
• Generally, PHP codes have a basic type of syntax like html as the first type of document.
PHP tag will be used in the html code; in the below PHP tag, we will write the logic
using PHP syntax and statements and finally, it will have the whitespace for comment
purposes. The view part will be shown like normal html codes because PHP codes are
written in script tags.
• PHP supports all type of web servers like Apache Tomcat, IIS Servers, Jetty etc. This
facility will be more comfortable for PHP application developers to develop a flexible
environment that will save more time. Compared to other application programming
languages, PHP will be deployed more easily, and hosting companies for the PHP will
be more the server of the hosted companies for running the PHP applications will be
less costly.
• The Market of PHP Applications are taken as less effort when compared to other high
complexity applications. It is one of the best features of the PHP language. In the Olden
Days, the market of web applications will take more time to reaching the market; it
takes fewer chances of getting more popular in the market, and competition also used
to be more on that time. Performance-wise will be more reliable with the user, so it is
an effective language for user perspectives.
• PHP is also the same as compared to other languages like java; they have their own
predefined functions and libraries. It has the feature like sending emails, connect with
other network services it will generate jpeg, gif images etc., and also it generates pdf,
excels documents for downloading the web page contents in the applications.
Example:1
<html>
<title>First Application of PHP</title>
<body>
<h3>Welcome To My Domain</h3>
<?php
?>
</body>
</html>
Output:
Example:2
<html>
<title>Sample Application</title>
<body>
<h3>Welcome To My Domain</h3>
<?php
?>
<p>Welcome</p>
<?php
?>
</body>
</html>
Output:
Example:3
<html>
<title>Sample Application</title>
<h3>Welcome To My Domain</h3>
<body>
<a href="first.php">Home</a>
?>
</body>
</html>
First.php
<?php
echo "Welcome"
?>
Second.php
<?php
echo "User"
?>
Output:
MySQL is one of the most popular relational databases, frequently used alongside PHP for
creating dynamic, data-driven websites and applications. PHP has built-in support for
connecting to MySQL databases, making it easy to store, retrieve, and manipulate data. In this
tutorial, we’ll cover how to connect to a MySQL database, perform CRUD operations, and use
prepared statements for security.
To work with PHP and MySQL, first ensure you have a MySQL server installed. If you’re
using XAMPP, WAMP, or MAMP, MySQL will be included.
2. Create a new database by entering a name (e.g., tutorial_db) and clicking "Create."
3. Inside your new database, create a table (e.g., users) with the following fields:
o age (INT)
sql
age INT
);
PHP provides multiple ways to connect to a MySQL database, with MySQLi (MySQL
Improved) being one of the most commonly used extensions. Here’s how to establish a
connection:
php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tutorial_db";
// Create connection
// Check connection
if ($conn->connect_error) {
?>
In this example:
• $conn is a new mysqli object that holds the connection to the MySQL server.
CRUD stands for Create, Read, Update, and Delete—the four essential operations for
managing data in a database. Let’s explore each of these using PHP and MySQLi.
php
<?php
$email = "[email protected]";
$age = 30;
$sql = "INSERT INTO users (name, email, age) VALUES ('$name', '$email', $age)";
} else {
?>
In this example:
• The SQL statement inserts a new row into the users table with values for name, email,
and age.
php
<?php
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "
- Age: " . $row["age"] . "<br>";
} else {
?>
In this example:
• The SQL statement SELECT * FROM users retrieves all columns from the users table.
3. Updating Data
php
<?php
$newAge = 35;
$userId = 1;
} else {
?>
In this example:
• The UPDATE statement changes the age of the user with id=1.
• The WHERE clause ensures that only the specified record is updated.
4. Deleting Data
php
<?php
$userId = 1;
} else {
?>
In this example:
• The DELETE statement removes the user with id=1 from the users table.
• The WHERE clause prevents deletion of all records, which would occur if omitted.
Using prepared statements helps prevent SQL injection attacks, a common vulnerability in
database-driven applications. Prepared statements use placeholders instead of directly
embedding variables into SQL queries.
php
<?php
$stmt = $conn->prepare("INSERT INTO users (name, email, age) VALUES (?, ?, ?)");
$email = "[email protected]";
$age = 28;
$stmt->execute();
$stmt->close();
?>
In this example:
• bind_param() binds variables to the placeholders. The ssi argument specifies the data
types: s for string, s for string, and i for integer.
• Using prepared statements ensures that user input is safely handled, preventing SQL
injection.
<?php
$stmt = $conn->prepare("SELECT id, name, email, age FROM users WHERE age > ?");
$stmt->bind_param("i", $minAge);
$minAge = 25;
$stmt->execute();
$result = $stmt->get_result();
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . " -
Age: " . $row["age"] . "<br>";
$stmt->close();
?>
In this example:
• The SQL statement selects users whose age is greater than the specified value.
• Using prepared statements with placeholders prevents SQL injection, making this a
safer way to handle queries with user inputs.
When you’re done with database operations, close the connection to free up resources.
<?php
$conn->close();
?>