Aditya PHP File
Aditya PHP File
Faculty Name: Dr. Farzil Kidwai Student Name: Priyanshu Singh Chilwal
Assistant Professor Roll No.: 00596407222
Semester: Seventh
Group: 7-CSE-FSD-2A
2024
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY
VISION
To nurture young minds in a learning environment of high academic value and imbibe spiritual and ethical values with
technological and management competence.
MISSION
The Institute shall endeavours to incorporate the following basic missions in the teaching methodology:
Practical exercises in all Engineering and Management disciplines shall be carried out by Hardware
equipment as well as the related software enabling deeper understanding of basic concepts and
encouraging inquisitive nature.
The Institute strives to match technological advancements and encourage students to keep updating their
knowledge for enhancing their skills and inculcating their habit of continuous learning.
The Institute endeavours to enhance technical and management skills of students so that they are intellectually
capable and competent professionals with Industrial Aptitude to face the challenges of globalization.
Diversification
The Engineering, Technology and Management disciplines have diverse fields of studies with different
attributes. The aim is to create a synergy of the above attributes by encouraging analytical thinking.
The Institute provides seamless opportunities for innovative learning in all Engineering and Management
disciplines through digitization of learning processes using analysis, synthesis, simulation, graphics,
tutorials and related tools to create a platform for multi-disciplinary approach.
Entrepreneurship
The Institute strives to develop potential Engineers and Managers by enhancing their skills and research
capabilities so that they become successful entrepreneurs and responsible citizens.
VISION
“To be centre of excellence in education, research and technology transfer in the field of
computer engineering and promote entrepreneurship and ethical values.”
MISSION
“To foster an open, multidisciplinary and highly collaborative research environment to
produce world-class engineers capable of providing innovative solutions to real life
problems
and fulfil societal needs.”
LABASSESSMENTSHEET
Sno. Experiment MARKS Total Date of Date of Teacher’s
marks Experiment submission signature
R1 R2 R3 R4 R5
1 a. Install and configure
PHP, web server,
MYSQL b. Write a
program to print
“Welcome to PHP”. c.
Write a simple PHP
program using
expressions and
operators.
2 Write a PHP program to
demonstrate the use of
Decision making control
structures using: a. If
statement b. If‐else
statement c. Switch
statement
3 Write a PHP program to
demonstrate the use of
Looping structures using:
a. while statement b.
do‐while statement c. for
statement d. foreach
statement
4 Write a PHP program for
creating and
manipulating‐ a.
Indexed array b.
Associative array c.
Multidimensional array
5 a. Write a PHP
program to‐ i. Calculate
length of string. ii. Count
the
number of words in string
without using string
functions. b. Write a
simple PHP program to
demonstrate use of
various built‐in string
functions.
6 Write a simple PHP
program to demonstrate
use of Simple function
and Parametrized
function.
9 Develop a simple
application to a. Enter
data into database. b.
Retrieve and present data
from database.
10 Develop a simple
application to Update,
Delete table data from
database.
Aim:
Experiment-1
Theory: To set up a PHP environment, you need to install a web server (like
Apache or Nginx), PHP, and MySQL. This stack, often referred to as LAMP (Linux,
Apache, MySQL, PHP), enables dynamic web applications. After installation,
configure the web server to process PHP files, typically found in the server's
document root. A simple PHP program to display a message uses the echo statement,
while expressions and operators can be demonstrated with arithmetic operations.
PHP is a server-side scripting language designed for web development but can also
be used for general-purpose programming.
Code:
<?php
echo "Welcome to PHP";
?>
Output:
Code:
<?php
$a = 10;
$b = 5;
$sum = $a + $b; // Addition
$difference = $a - $b; // Subtraction
$product = $a * $b; // Multiplication
$quotient = $a / $b; // Division
$remainder = $a % $b; // Modulus echo
"Addition: $a + $b = $sum\n"; echo
"Subtraction: $a - $b = $difference\n"; echo
"Multiplication: $a * $b = $product\n"; echo
"Division: $a / $b = $quotient\n"; echo
"Remainder: $a % $b = $remainder\n"; ?>
Output:
Aim:
Experiment-2
A. If statement:
Code:
<?php $age =
20; if ($age >=
18) {
echo "You are an adult.";
}
?>
Output:
B. If-else Statement:
Code:
<?php $number = 5; if
($number % 2 == 0) {
echo "$number is even.";
Aim: Write
} else {
echo "$number is odd.";
}
?>
Output:
C. Switch Statements:
Code:
<?php $day = 3;
switch ($day) { case
1: echo "Monday";
break;
case 2: echo
"Tuesday";
break;
case 3: echo
"Wednesday";
break;
default:
echo "Another day";
}
?>
Output:
Experiment-3
Theory: Looping structures in PHP allow you to execute a block of code repeatedly
based on certain conditions. The while statement continues to execute as long as the
specified condition is true. The do-while statement functions similarly but
guarantees at least one execution of the loop body, as the condition is checked after
the loop's body runs.
a. While statement:
Code:
<?php $count = 1;
while ($count <= 5) {
echo "Count is: $count\n";
$count++;
}
?>
Output:
b. Do while Statement:
Code:
<?php
$count = 1;
do {
echo "Count is: $count\n";
$count++;
Aim: Write
c. For Statements:
Output:
Code:
<?php
$fruits = array("Apple", "Banana", "Cherry");
foreach ($fruits as $fruit) {
echo "Fruit: $fruit\n";
}
?>
Output:
Experiment-4
Theory: In PHP, arrays are versatile data structures that can hold multiple values.
Indexed arrays store values with numeric indices, allowing for easy access and
iteration. They are useful when the order of elements matters. Associative arrays
utilize named keys instead of numeric indices, enabling more meaningful access to
data by associating values with specific labels, making them ideal for key-value
pairs. Multidimensional arrays are arrays that contain other arrays, facilitating the
organization of complex data structures like matrices or tables.
a. Indexed Array:
Code:
<?php
$colors = array("Red", "Green", "Blue");
$colors[] = "Yellow";
unset($colors[1]); echo
"Indexed Array:\n"; foreach
($colors as $color) { echo
"$color\n";
}
?>
Output:
b. Associative array:
Code:
Aim: Write
<?php
$person = array(
"name" => "John Doe",
"age" => 30,
"city" => "New York"
);
$person["age"] = 31;
$person["occupation"] = "Developer";
echo "Associative Array:\n"; foreach
($person as $key => $value) {
echo "$key: $value\n";
}
?>
Output:
c. Multidimensional Array:
Code:
<?php
$students = array( array("name" =>
"Alice", "age" => 20), array("name" =>
"Bob", "age" => 22),
array("name" => "Charlie", "age" => 23)
);
$students[1]["age"] = 23;
$students[] = array("name" => "David", "age" => 21);
echo "Multidimensional Array:\n";
foreach ($students as $student) {
echo "Name: " . $student["name"] . ", Age: " . $student["age"] . "\n";
}
?>
Output:
Experiment-5
Theory: In PHP, strings are sequences of characters used to represent text. The
length of a string can be determined by counting the number of characters it contains,
which can be done through iteration rather than built-in functions. Counting words
in a string involves identifying spaces between words and tallying the transitions
from non-space to space characters. PHP also provides numerous built-in string
functions that simplify string manipulation. Functions like strlen() determine string
length, strtoupper() and strtolower() convert cases, str_replace() replaces substrings,
and substr() extracts portions of strings.
a. Program for
I. Calculate length of string:
Code:
<?php
$string = "Hello, World!";
$length = 0;
for ($i = 0; isset($string[$i]); $i++) {
$length++;
}
echo "Length of the string: $length\n";
?>
Output:
II. Count the number of words in string without using string functions.
Code:
<?php
$string = "This is a sample string";
$wordCount = 0;
$inWord = false;
for ($i = 0; isset($string[$i]); $i++) {
if ($string[$i] !== ' ') {
if (!$inWord) {
$inWord = true;
$wordCount++;
}
} else {
$inWord = false;
}
}
echo "Number of words in the string: $wordCount\n";
?>
Output:
Code:
<?php
// Demonstrating various built-in string functions
$string = "Hello, World!";
Output:
Experiment-6
Aim: Write a simple PHP program to demonstrate use of Simple function and
Parametrized function
Theory: Functions in PHP are reusable blocks of code that perform specific tasks,
helping to organize and simplify programming. A simple function does not require
any parameters; it can be called without passing any values, allowing it to execute
predefined actions, such as printing messages. In contrast, a parameterized function
accepts inputs (parameters) when called, enabling it to perform operations based on
the values provided. This flexibility allows for more dynamic and versatile code, as
the same function can operate on different data. Functions enhance code readability
and maintainability, making them a fundamental concept in PHP programming and
software development.
Code:
<?php
// Simple function: Prints a greeting message
function greet() {
echo "Hello, welcome to the PHP programming world!\n";
}
Output:
Experiment-7
Theory: Data validation in PHP is crucial for ensuring that user inputs are accurate
and secure before processing them. It involves checking the data provided by users
against predefined rules to prevent errors and protect against malicious inputs.
Common validation techniques include checking for empty fields, ensuring the
correct format (e.g., email addresses), and sanitizing inputs to avoid security
vulnerabilities like SQL injection. PHP offers built-in functions like filter_var() for
validating and sanitizing data effectively. Implementing robust data validation
enhances the reliability of web applications, improving user experience while
safeguarding against invalid data submissions and potential threats.
Code:
<?php
$name = $email = "";
$nameErr = $emailErr = "";
$valid = true;
// Process form data when submitted if
($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty(trim($_POST["name"]))) {
$nameErr = "Name is required.";
$valid = false;
} else {
$name = trim($_POST["name"]);
}
if (empty(trim($_POST["email"]))) {
$emailErr = "Email is required.";
$valid = false;
} elseif (!filter_var(trim($_POST["email"]), FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format.";
$valid = false;
} else {
$email = trim($_POST["email"]);
}
Aim:
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Data Validation Example</title>
</head>
<body>
<h2>Simple Form with Data Validation</h2>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"
method="post">
<div>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo
htmlspecialchars($name); ?>">
<span style="color:red;"><?php echo $nameErr; ?></span>
</div> <div>
<label for="email">Email:</label>
<input type="text" name="email" value="<?php echo
htmlspecialchars($email); ?>">
<span style="color:red;"><?php echo $emailErr; ?></span>
</div> <div>
<input type="submit" value="Submit">
</div> </form>
<?php
if ($valid && $_SERVER["REQUEST_METHOD"] == "POST")
{ echo "<h3>Submitted Data:</h3>"; echo "Name: " .
htmlspecialchars($name) . "<br>"; echo "Email: " .
htmlspecialchars($email) . "<br>"; }
?>
</body></html>
Output:
Experiment - 8
Theory: Cookies and sessions are essential for maintaining state in PHP
applications. Cookies are small text files stored on the client-side, used to remember
user information across sessions, such as preferences or login details. They are set
using setcookie() and can be accessed via the $_COOKIE superglobal. Sessions, on
the other hand, store data on the server-side, enabling temporary data storage for
individual users. Sessions are initiated with session_start() and data is accessed using
the $_SESSION superglobal. They are beneficial for tracking user activities without
exposing sensitive data to the client, enhancing security in web applications.
Code:
<?php
// Set a cookie
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1
day
Output:
Code:
<?php
// Start the session
session_start();
Output:
Experiment-9
Code:
<?php
$servername = "localhost"; // Change to your database host if necessary
$username = "your_database_username"; // Replace with your database username
$password = "your_database_password"; // Replace with your database password
$dbname = "your_database_name"; // Replace with your database name
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$sql = "CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL
)";
$conn->exec($sql);
$name = $email = "";
Aim:
if ($stmt->execute()) {
$successMessage = "New record created successfully.";
} else {
$errorMessage = "Error: " . $stmt->errorInfo()[2];
}
}
} catch (PDOException $e) {
$errorMessage = "Connection failed: " . $e->getMessage();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Enter Data</title>
</head>
<body>
<h2>Enter User Data</h2>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"
method="post">
<label for="name">Name:</label>
<input type="text" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" name="email" required><br><br>
<input type="submit" value="Submit">
</form>
<?php
if (!empty($successMessage)) {
echo "<p style='color:green;'>$successMessage</p>";
}
if (!empty($errorMessage)) {
echo "<p style='color:red;'>$errorMessage</p>";
}
?>
</body>
</html>
Output:
Code:
<?php
// Simulated user data (normally you would retrieve this from a database)
$users = [
['id' => 1, 'name' => 'John Doe', 'email' => '[email protected]'],
['id' => 2, 'name' => 'Jane Smith', 'email' => '[email protected]'],
['id' => 3, 'name' => 'Alice Johnson', 'email' => '[email protected]']
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simulated User Data</title>
</head>
<body>
<h2>User Data</h2>
<?php displayUsers($users); ?>
</body>
</html>
Output:
Experiment - 10
Aim: Develop a simple application to Update, Delete table data from database.
Theory: A simple application to update and delete data from a database allows users
to manage their data effectively. Updating involves changing existing records, while
deleting removes records entirely. These operations are crucial for maintaining
accurate and relevant information within the database. Using SQL commands, such
as UPDATE and DELETE, these actions can be performed safely and efficiently.
Proper validation and confirmation messages are essential to prevent accidental data
loss. In PHP, these operations can be integrated with HTML forms to enable user
interaction, allowing users to select which records to modify or remove easily.
Code:
<?php
// Simulated database using an array
$users = [
["id" => 1, "name" => "John Doe", "email" => "[email protected]"],
["id" => 2, "name" => "Jane Smith", "email" => "[email protected]"],
];
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Update and Delete User Data</title>
</head>
<body>
<h2>User Data</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
<?php foreach ($users as $user): ?>
<tr>
<td><?php echo htmlspecialchars($user['id']); ?></td>
<td><?php echo htmlspecialchars($user['name']); ?></td>
<td><?php echo htmlspecialchars($user['email']); ?></td>
<td>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $user['id']; ?>">
<input type="text" name="name" value="<?php echo
htmlspecialchars($user['name']); ?>" required>
<input type="email" name="email" value="<?php echo
htmlspecialchars($user['email']); ?>" required>
<input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete" onclick="return
confirm('Are you sure you want to delete this user?');">
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php
// Display success message
if ($successMessage) {
echo "<p style='color:green;'>$successMessage</p>";
}
?>
</body>
</html>
Output: