0% found this document useful (0 votes)
21 views40 pages

Unit III Full Stack

This document provides an introduction to PHP, covering its features, functionalities, and applications in web development. It includes explanations of PHP expressions, control flow statements, functions, and the workflow of PHP in generating dynamic content. Additionally, it discusses the advantages and limitations of PHP, along with practical examples and exercises for hands-on learning.

Uploaded by

stark9994727589
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views40 pages

Unit III Full Stack

This document provides an introduction to PHP, covering its features, functionalities, and applications in web development. It includes explanations of PHP expressions, control flow statements, functions, and the workflow of PHP in generating dynamic content. Additionally, it discusses the advantages and limitations of PHP, along with practical examples and exercises for hands-on learning.

Uploaded by

stark9994727589
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

UNIT 3 12 Hrs.

Introduction to PHP. -Expressions and Control Flow in PHP. -PHP Functions and

Objects-PHP Arrays- GET, POST variables- Embedding PHP- PHP and MySQL

Practice:

1. Write a PHP script to : -

a) transform a string all uppercase letters

b)transform a string all lowercase letters.

2. Write a PHP script to remove comma(s) from the following numeric string

3. Write a PHP script to remove part of a 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

echo "Hello, World!";

?>

Output:

Hello, World!

How PHP Works?


Below are the following steps, which show how PHP works:

Step 1: User Requests the Page

• The user enters a URL into a web browser or clicks on a link, making an HTTP request
to the web server.

Step 2: Web Server Receives the Request

• The web server (Apache, Nginx, etc.) receives the HTTP request. The request is
directed to PHP for processing.

• The PHP script located on the server is executed.

Step 3: PHP Processes the Request

• 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.

Step 4: Database Interaction

• 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.

Step 5: PHP Responds with Dynamic Content


• Based on the database response, the PHP script processes and prepares the output
(dynamic HTML or other content) that will be sent back to the user's browser.

• This response is returned as an HTTP response to the web browser.

Step 6: Web Browser Receives the Response

• The web browser receives the HTTP response, which includes dynamic content
generated by PHP.

• The browser renders the content on the user's screen.

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.

What is a PHP File?

• A PHP file containing PHP code which is used to create dynamic web pages.

• It contains HTML, CSS, JavaScript and PHP code together.

• It Runs on a web server with PHP installed (e.g., Apache, Nginx) and the output is sent
to the browser as plain HTML.

• It is saved with a .php extension.

What Can PHP Do?

• 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.

• Encrypt Data: PHP can encrypt sensitive information for security.

Why is PHP still popular?

• 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.

• WordPress Backend: PHP is the foundation of WordPress, used by 75% of CMS-based


websites.

• Integrates Easily: Works well with HTML and JavaScript to build dynamic websites.

• Fast Performance: PHP 8 introduced Just-In-Time (JIT) compilation for faster


execution.

PHP is a Loosely Typed Language

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.

• In PHP 7, type declarations were introduced.

• 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.

Key Features of PHP

• 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.

• Database Handling: PHP easily connects to databases


like MySQL, PostgreSQL and SQLite, allowing for efficient data management and
storage in web applications.

• 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.

• Command-Line Scripting: PHP can be used to write command-line scripts for


automating repetitive tasks, such as data processing or system monitoring.

• Game Development: PHP is used for backend logic in browser-based multiplayer


games, handling user authentication, scores, and game state.

• 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

An expression is a combination of values, variables, operators, and functions that results in a


value. It’s familiar to anyone who has taken high-school algebra. Here’s an example:

y = 3 (|2x| + 4)

Which in PHP would be:

$y = 3 * (abs(2 * $x) + 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

echo "a: [" . (20 > 9) . "]<br>";

echo "b: [" . (5 == 6) . "]<br>";

echo "c: [" . (1 == 0) . "]<br>";

echo "d: [" . (1 == 1) . "]<br>";

?>

The output from this code is as follows:

a: [1]

b: []

c: []

d: [1]

Example 2. Outputting the values of TRUE and FALSE

<?php // test2.php

echo "a: [" . TRUE . "]<br>";


echo "b: [" . FALSE . "]<br>";

?>

Output:

a: [1]

b: []

PHP Literals and Variables

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.

Example: Literals and variables

<?php

$myname = "Brian";

$myage = 37;

echo "a: " . 73 . "<br>"; // Numeric literal

echo "b: " . "Hello" . "<br>"; // String literal

echo "c: " . FALSE . "<br>"; // Constant literal

echo "d: " . $myname . "<br>"; // String variable

echo "e: " . $myage . "<br>"; // Numeric variable

?>

Output:

a: 73

b: Hello

c:

d: Brian
e: 37

Example: An expression and a statement

<?php

$days_to_new_year = 366 - $day_number; // Expression

if ($days_to_new_year < 30)

echo "Not long now till new year"; // Statement

?>

Control Flow statement in 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) {

// code to be executed if condition is true

} else {

// code to be executed if condition is false

syntax for multiple if-else statement:

if (condition1) {

// code to be executed if condition1 is true


} elseif (condition2) {

// code to be executed if condition2 is true

} else {

// code to be executed if all conditions are false

Example:

<?php

$num = 10;

if ($num < 5) {

echo "The number is less than 5.";

} elseif ($num == 5) {

echo "The number is equal to 5.";

} else {

echo "The number is greater than 5.";

?>

Output:

The number is greater than 5.

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:

// code to be executed if expression is equal to value1

break;

case value2:
// code to be executed if expression is equal to value2

break;

default:

// code to be executed if expression is not equal to any of the values

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':

echo 'Today is Monday';

break;

case 'Tuesday':

echo 'Today is Tuesday';

break;

case 'Wednesday':

echo 'Today is Wednesday';

break;

case 'Thursday':

echo 'Today is Thursday';

break;
case 'Friday':

echo 'Today is Friday';

break;

default:

echo 'It is the weekend';

?>

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:

for (initialization; condition; increment) {

// 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

for ($i = 1; $i <= 10; $i++) {

echo $i . " ";

?>

Output:
1 2 3 4 5 6 7 8 9 10

Break and Continue Statements Inside a For Loop

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

for ($i = 1; $i <= 10; $i++) {

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;

while ($count <= 5) {

echo $count . " ";

$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 {

echo $count . " ";

$count++;

} while ($count <= 5);

?>

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.

• PHP functions allow code reusability by encapsulating a block of code to perform


specific tasks.

• 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.

Creating a Function in PHP


A function is declared by using the function keyword, followed by the name of the function,
parentheses (possibly containing parameters), and a block of code enclosed in curly braces.

Syntax

function functionName($param1, $param2) {


// Code to be executed
return $result; // optional
}

Calling a Function in PHP

Once a function is declared, it can be invoked (called) by simply using the function name
followed by parentheses.

<?php

function sum($a, $b) {

return $a + $b;

echo sum(5, 3); // Outputs: 8

?>

Output:

Returning Values in PHP Functions

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

function multiply($a, $b) {

return $a * $b;
}

$result = multiply(4, 5); // $result will be 20

echo $result; // Output: 20

?>

Output

20

Anonymous Functions (Closures)

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.

Now, let us understand with the help of example:

<?php

$greet = function($name) {

echo "Hello, " . $name . "!";

};

$greet("GFG");

?>

Output

Hello, GFG!

In this example:

• An anonymous function is defined and assigned to the variable $greet.

• The function takes $name as a parameter and prints a greeting message.

• 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 {

return $n * factorial($n - 1);

echo factorial(5);

?>

Output

120

In this example:

• The function factorial() is defined to calculate the factorial of a number $n using


recursion.

• If $n is 0, the function returns 1 (base case); otherwise, it calls itself with $n - 1.

• When factorial(5) is called, the function recursively multiplies 5 * 4 * 3 * 2 * 1,


returning 120.

Common PHP Functions

Here are some common PHP functions you should know:


1. String Functions

• strlen(): Returns the length of a string.

• strtoupper(): Converts a string to uppercase.

• strtolower(): Converts a string to lowercase.

• substr(): Returns a part of a string.

2. Array Functions

• array_push(): Adds elements to the end of an array.

• array_pop(): Removes the last element of an array.

• array_merge(): Merges two or more arrays.

3. Date and Time Functions

• date(): Returns the current date or time.

• strtotime(): Converts a string into a Unix timestamp.

• time(): Returns the current Unix timestamp.

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:

$objectName = new ClassName();

Example:

<?php

class Car {

public $brand;

public $model;
public function drive() {

echo "Driving the $this->brand $this->model.";

// Create an object (instance) of the Car class

$myCar = new Car();

$myCar->brand = "Toyota"; // Set the brand property

$myCar->model = "Corolla"; // Set the model property

// Access the method of the object

$myCar->drive();

?>

Output:

Driving the Toyota Corolla.

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 are dynamically sized.

• They allow you to store multiple values in a single variable, making it easier to manage
related data.
Types of Arrays in PHP

There are three main 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.

Now, let us understand with the help of the example:

<?php

$fruits = array("apple", "banana", "cherry");

echo $fruits[0]; // Outputs: apple

?>

Output

apple

You can also explicitly define numeric keys in an indexed array:

<?php

$fruits = array(0 => "apple", 1 => "banana", 2 => "cherry");

?>

2. Associative Arrays

Associative arrays use named keys, which are useful when you want to store data with
meaningful identifiers instead of numeric indexes.

Now, let us understand with the help of the example:

<?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.

Now, let us understand with the help of the example:

<?php

$students = array(

"Anjali" => array("age" => 25, "grade" => "A"),

"GFG" => array("age" => 22, "grade" => "B")

);

echo $students["GFG"]["age"];

?>

Output

22

Creating Array in PHP

In PHP, arrays can be created using two main methods:

1. Using the array() function

The traditional way of creating an array is using the array() function.

$fruits = array("apple", "banana", "cherry");

2. Using short array syntax ([])

In PHP 5.4 and later, you can use the shorthand [] syntax to create arrays.

$fruits = ["apple", "banana", "cherry"];


You can also create associative arrays by specifying custom keys:

$person = ["name" => "GFG", "age" => 30];

Note: Both methods are valid, but the shorthand syntax is preferred for its simplicity and
readability.

Accessing and Modifying Array Elements

1. Accessing Array Elements

You can access individual elements in an array using their index (for indexed arrays) or key
(for associative arrays).

• Accessing Indexed Array:

$fruits = ["apple", "banana", "cherry"];


echo $fruits[0]; // Outputs: apple

• Accessing Associative Array:

$person = ["name" => "GFG", "age" => 30];


echo $person["name"]; // Outputs: GFG

2. Modifying Array Elements

You can modify an existing element by assigning a new value to a specific index or key.

• Modifying Indexed Array Element:

$fruits = ["Apple", "Banana", "Cherry"];


$fruits[1] = "Mango"; // Changes "Banana" to "Mango"
echo $fruits[1]; // Outputs: Mango

• Modifying Associative Array Element:

$person = ["name" => "GFG", "age" => 25];


$person["age"] = 26; // Updates the age to 26
echo $person["age"]; // Outputs: 26

Adding and Removing Array Items

1. Adding Array Elements

You can add new elements to an array using the following methods:
• array_push(): Adds elements to the end of an indexed array.

$fruits = ["apple", "banana"];


array_push($fruits, "cherry"); // Adds "cherry" to the end

• array_unshift(): Adds elements to the beginning of an indexed array.

array_unshift($fruits, "pear"); // Adds "pear" to the beginning

• Direct assignment: Adds an element to an associative array.

$person["city"] = "New York";

2. Removing Array Elements

To remove items from an array, you can use several functions:

• array_pop(): Removes the last element from an indexed array.

array_pop($fruits);

• array_shift(): Removes the first element from an indexed array.

array_shift($fruits);

• unset(): Removes a specific element from an array by key or index.

unset($fruits[2]); // Removes the element with index 2

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.

$array1 = [1, 2, 3];


$array2 = [4, 5, 6];
$merged = array_merge($array1, $array2);
print_r($merged); // Outputs: [1, 2, 3, 4, 5, 6]

• Array Search: The in_array() function checks if a specific value exists in an array.

$fruits = ["Apple", "Banana", "Cherry"];


if (in_array("Banana", $fruits)) {
echo "Banana is in the array!";
}

• Array Sort: The sort() function sorts an indexed array in ascending order.

$numbers = [3, 1, 4, 1, 5];


sort($numbers);
print_r($numbers); // Outputs: [1, 1, 3, 4, 5]

Array Iteration

You can loop through arrays using loops such as foreach or for.

• Using foreach Loop:

$fruits = ["Apple", "Banana", "Cherry"];


foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}

• Using for Loop:

$numbers = [1, 2, 3, 4];


for ($i = 0; $i < count($numbers); $i++) {
echo $numbers[$i] . "<br>";
}

GET, POST variables in PHP

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.

• Accessed using associative array notation, e.g., $_GET['parameter'].

Syntax:

<?php

echo $_GET['username']; // Outputs the value of the 'username' parameter from the URL

?>

Example:

<html>

<body>

<form action="index.php" method="get">

<label>username:</label><br>

<input type="text" name="username"><br>

<input type="submit" value="Log in"><br>

</form>

</body>

</html>

<?php

echo "{$_GET["username"]} <br>" ;

?>

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.

• The form includes a text input field for the username.

• The submit button sends the form data when clicked.

• 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>

<form action="index.php" method="post">

<label>username:</label><br>

<input type="text" name="username"><br>

<input type="submit" value="Log in"><br>

</form>

</body>

</html>

<?php

echo "{$_POST["username"]} <br>" ;

?>

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.

• The form includes a text input field for the username.

• The submit button sends the form data when clicked.

• 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.

When to Use $_GET and $_POST

Use $_GET:

• For data like search terms or filter criteria that don't need security.

• Best for short data (due to URL length limits).

• 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.

• Suitable for forms with larger data, such as file uploads.

• Use for submitting forms that change server-side data (e.g., registration forms).

• Prevents data from being cached or stored in browser history.

$_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

Limited by URL length Can handle large data sizes

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.

How to use Embed PHP in HTML?

• 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.

Importance of Embed PHP in HTML

• PHP is also used as a command-line code script written in desktop applications or


standalone applications but mainly focuses on web-based applications. Normally the
client user sends the request to the server; the request itself has the PHP code is
happened, the response will be in either xml or json type it will become from the server.
PHP is used for creating dynamic web sites.
• We probably know that PHP can create dynamic websites, and PHP is quite easy to
learn when compared to other server-side languages. PHP is open-source, and its
components are free for usages and also easily available in the open-source market.
Hence opensource, we will use PHP. The free syntax is very easy to use. PHP runs all
type of Operating Systems like Windows, MacoX, Linux and Sun Solaris etc. it is one
of the main benefits of PHP.

• 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.

• PHP applications are more user-friendly because it is easy to understand and it is


simplicity one. It is also one of the ways to secure web applications and websites; it has
a security layer to protect against threats, malwares etc when compared to other
languages, it has more secured. It has an Extension feature for user support, and it is
easy to integrate.

Examples of Embed PHP in HTML

Example:1

<html>
<title>First Application of PHP</title>

<body>

<h3>Welcome To My Domain</h3>

<?php

echo "Welcome User";

?>

</body>

</html>

Output:

Example:2

<html>

<title>Sample Application</title>

<body>

<h3>Welcome To My Domain</h3>

<?php

echo "Welcome Users.";

?>

<p>Welcome</p>

<?php

$examp = "Welcome Users";

echo " $examp.";

?>

</body>
</html>

Output:

Example:3

<html>

<title>Sample Application</title>

<h3>Welcome To My Domain</h3>

<body>

<a href="first.php">Home</a>

<?php include "first.php";

?> <a href="second.php">contactus</a>

<?php include "second.php"

?>

</body>

</html>

First.php

<?php

echo "Welcome"

?>

Second.php

<?php

echo "User"

?>
Output:

PHP and SQL

Introduction to PHP and MySQL

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.

Setting Up a MySQL Database

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.

1. Open phpMyAdmin (usually accessible at http://localhost/phpmyadmin).

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 id (INT, primary key, auto-increment)

o name (VARCHAR, length: 100)

o email (VARCHAR, length: 100)

o age (INT)

Your table should look like this:

sql

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100) NOT NULL,


email VARCHAR(100) NOT NULL,

age INT

);

Connecting PHP to MySQL

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:

Example: Database Connection with MySQLi

php

<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "tutorial_db";

// Create connection

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

// Check connection

if ($conn->connect_error) {

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

echo "Connected successfully";

?>

In this example:

• $conn is a new mysqli object that holds the connection to the MySQL server.

• If the connection fails, an error message will display using $conn->connect_error.


• Replace root and "" with your MySQL username and password if they differ.

Basic CRUD Operations with MySQLi

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.

1. Creating (Inserting) Data

The INSERT INTO SQL statement adds new records to a table.

Example: Inserting Data into the Database

php

<?php

// Insert a new user

$name = "John Doe";

$email = "[email protected]";

$age = 30;

$sql = "INSERT INTO users (name, email, age) VALUES ('$name', '$email', $age)";

if ($conn->query($sql) === TRUE) {

echo "New record created successfully";

} else {

echo "Error: " . $sql . "<br>" . $conn->error;

?>

In this example:

• The SQL statement inserts a new row into the users table with values for name, email,
and age.

• $conn->query($sql) executes the SQL statement.


2. Reading (Selecting) Data

The SELECT SQL statement retrieves data from the database.

Example: Retrieving Data from the Database

php

<?php

$sql = "SELECT id, name, email, age FROM users";

$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 {

echo "No records found";

?>

In this example:

• The SQL statement SELECT * FROM users retrieves all columns from the users table.

• $result->fetch_assoc() fetches each row as an associative array, making it easy to access


column values.

3. Updating Data

The UPDATE SQL statement modifies existing records.

Example: Updating Data in the Database

php
<?php

$newAge = 35;

$userId = 1;

$sql = "UPDATE users SET age=$newAge WHERE id=$userId";

if ($conn->query($sql) === TRUE) {

echo "Record updated successfully";

} else {

echo "Error updating record: " . $conn->error;

?>

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

The DELETE SQL statement removes records from the table.

Example: Deleting Data from the Database

php

<?php

$userId = 1;

$sql = "DELETE FROM users WHERE id=$userId";

if ($conn->query($sql) === TRUE) {

echo "Record deleted successfully";

} else {

echo "Error deleting record: " . $conn->error;


}

?>

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 for Security

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.

Example: Inserting Data with Prepared Statements

php

<?php

$stmt = $conn->prepare("INSERT INTO users (name, email, age) VALUES (?, ?, ?)");

$stmt->bind_param("ssi", $name, $email, $age);

$name = "Jane Smith";

$email = "[email protected]";

$age = 28;

$stmt->execute();

echo "New record created successfully";

$stmt->close();

?>

In this example:

• prepare() creates a prepared statement with placeholders (?).

• 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.

Example: Retrieving Data with Prepared Statements

<?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();

while ($row = $result->fetch_assoc()) {

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.

Closing the Database Connection

When you’re done with database operations, close the connection to free up resources.

<?php

$conn->close();

?>

You might also like