0% found this document useful (0 votes)
58 views

PHP lab

Uploaded by

Deepesh
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)
58 views

PHP lab

Uploaded by

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

Guru Tegh Bahadur Institute of Technology, Delhi

(Affiliated to Guru Gobind Singh Indraprastha University, Dwarka, New Delhi)

PHP Programming and MySQL Lab


Paper Code: FSD‐435P

Academic Year: 2024-2025


Semester: 7th

Submitted To: Submitted By:

Ms. Jyotsana Mam Name: Gyanesh Kumar


Assistant Professor Roll No.: 05876802721

Guru Tegh Bahadur Institute of Technology


Department of Computer Science & Engineering
INDEX
S. List of Experiments Date T. Sign
No.
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 W rite 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.
7 Develop web page with data validation.

8 Write simple PHP program to-


a. Set cookies and read it.
b. Demonstrate session management
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.
Experiment -1
Aim:
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.

Theory:
➢ Install and configure PHP, web server, MYSQL

XAMPP is a free, open-source cross-platform web server solution stack package developed by
Apache Friends. It primarily includes:

1. Apache - Web server


2. MySQL (MariaDB) - Database
3. PHP and Perl - Scripting languages

XAMPP is widely used for local development as it provides an easy way to set up a LAMP-like
stack on Windows, macOS, or Linux without complex configuration. Here’s a summary of its
components and features:

Key Components:

• Apache: Hosts websites and serves files over HTTP.


• MySQL/MariaDB: Database for storing site content, configuration, and other
application data.
• PHP: Server-side scripting language to handle dynamic content.
• Perl: Another scripting language, less commonly used for web, but supported in
XAMPP.
• phpMyAdmin: Web-based interface for managing MySQL databases.
• FileZilla FTP Server: Optional, for FTP services.
• Tomcat: Optional, for running Java Servlets and JSP.

Common Configurations:

• Change Apache Port: Modify Listen 80 in httpd.conf if port 80 is in use.


• Modify PHP Settings: Adjust php.ini in the php folder to configure PHP parameters
(e.g., max upload size).
• Database Access: Use phpMyAdmin to manage databases at
http://localhost/phpmyadmin.
Installation and Use:

1. Download: Get XAMPP from the official Apache Friends website.

2. Install: Follow the installation wizard to set up XAMPP on your machine.


3. Control Panel: XAMPP Control Panel allows you to start/stop individual components,
manage configuration files, and view logs.

1. PHP Configuration

• File Location: xampp/php/php.ini


• Key Settings to Modify:
o Maximum File Upload Size: Find and modify upload_max_filesize and
post_max_size to increase file upload limits.
o Error Reporting: Adjust error_reporting to control the types of PHP errors
displayed (e.g., E_ALL for all errors).
o Memory Limit: Modify memory_limit if your PHP scripts require more
memory.
o Execution Time: Change max_execution_time to prevent PHP scripts from
timing out too quickly.

2. Apache Configuration

• File Location: xampp/apache/conf/httpd.conf


• Key Settings to Modify:
o Server Port: By default, Apache uses port 80. To change it, locate Listen 80
in httpd.conf and replace 80 with a different port (e.g., 8080).
o Virtual Hosts: You can configure multiple domains/sites on your local server. To
do this, edit xampp/apache/conf/extra/httpd-vhosts.conf and define
each virtual host.
o Directory Permissions: Modify settings like AllowOverride to enable or
disable .htaccess overrides and control access permissions for specific
directories.
3. MySQL Configuration

• File Location: xampp/mysql/bin/my.ini


• Key Settings to Modify:
o Port Number: The default MySQL port is 3306. To change it, locate the port
setting and replace 3306 with a different port if needed.
o Buffer Sizes: Adjust settings like key_buffer_size, query_cache_size,
and innodb_buffer_pool_size to improve MySQL performance based on
your application’s requirements.
o Character Set: To set a default character set, look for character-set-server
and set it to your desired encoding (e.g., utf8mb4).

➢ Program to Print "Welcome to PHP"

<?php

echo "Welcome to PHP";

?>

Output:
➢ Write a simple PHP program using expressions and operators.
<?php
// Variables
$a = 10;
$b = 5;

// Arithmetic Operations
$sum = $a + $b;
$difference = $a - $b;
$product = $a * $b;
$division = $a / $b;

// Output results
echo "Sum: $sum<br>";
echo "Difference: $difference<br>";
echo "Product: $product<br>";
echo "Division: $division<br>";

// Comparison Operator
echo "Is A greater than 8? ";
echo ($a > 8) ? "Yes" : "No";
echo "<br>";

// Logical Operator
$isPositive = ($a > 0) && ($b > 0);
echo "Are both A and B positive? ";
echo ($isPositive) ? "Yes" : "No";
?>
Output:
Experiment -2
Aim:
Write a PHP program to demonstrate the use of Decision making control structures using:
a. If statement
b. If-else statement
C. Switch statement

Theory:
➢ If statement
<?php
$number = 10;
if ($number > 0) {
echo "$number is a positive number.";
}
?>

Output:
➢ If-else statement
<?php
$number = 15;
if ($number % 2 == 0) {
echo "$number is an even number.";
} else {
echo "$number is an odd number.";
}
?>

Output:

➢ Switch statement
<?php
$day = 3;
switch ($day) {
case 1:
echo "Sunday"; break;
case 2:
echo "Monday"; break;
case 3:
echo "Tuesday"; break;
case 4:
echo "Wednesday"; break;
case 5:
echo "Thursday"; break;
case 6:
echo "Friday"; break;
case 7:
echo "Saturday"; break;
default:
echo "Invalid day number!"; break;
}
?>

Output:
Experiment -3
Aim:
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

Theory:
➢ while statement
<?php
$number = 1;
while ($number <= 5) {
echo "Number: $number<br>"; // Corrected to use the variable within the string
$number++;
}
?>

Output:
➢ do-while statement
<?php
$number = 1;
do {
echo "Number: $number<br>"; // This will print the value of $number
$number++; // Increment the number
} while ($number <= 5); // Continue looping while $number is less than or equal to 5
?>

Output:

➢ for statement
<?php
for ($i = 1; $i <= 7; $i++) {
echo "Number: $i<br>"; // This will print the value of $i
}
?>
Output:

➢ foreach statement
<?php
$colors = array("Red", "Green", "Blue", "Yellow");
foreach ($colors as $color) {
echo "Color: $color<br>"; // Print each color from the array
}
?>

Output:
Experiment -4
Aim:
Write a PHP program for creating and manipulating-
a. Indexed array
b. Associative array
c. Multidimensional array

Theory:
➢ Indexed array
<?php
// Creating an indexed array
$fruits = ["Apple", "Banana", "Cherry", "Date", "Fig"];

// Adding an element to the array


$fruits[] = "Grapes";

// Removing an element from the array (removes "Cherry")


unset($fruits[2]);

// Modifying an element (change "Banana" to "Blueberry")


$fruits[1] = "Blueberry";

// Displaying the array


echo "Indexed Array:<br>";
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
?>
Output:

➢ Associative array
<?php
// Creating an associative array
$person = ["name" => "Om", "age" => 20, "city" => "Delhi"];
$person["country"] = "INDIA";

// Modifying a value
$person["age"] = 24;

// Removing a key-value pair


unset($person["city"]);
echo "Associative Array: <br>";
foreach ($person as $key => $value) {
echo $key . ": " . $value . "<br>";
}
?>
Output:

➢ Multidimensional array
<?php
// Creating a multidimensional array for students
$students = [
["name" => "Om", "age" => 24, "grade" => "A"],
["name" => "Sushant", "age" => 22, "grade" => "B"],
["name" => "Jaspreet", "age" => 21, "grade" => "C"]
];

// Adding a new student


$students[] = ["name" => "Manish", "age" => 21, "grade" => "D"];

// Modifying a student's grade


$students[1]["grade"] = "A";

// Removing a student
unset($students[2]);

// Displaying the array


echo "Multidimensional Array: <br>";
foreach ($students as $student) {
echo "Name: " . $student["name"] . ", Age: " . $student["age"] . ", Grade: " .
$student["grade"] . "<br>";
}
?>

Output:
Experiment -5
Aim:
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.

Theory:
➢ Write a PHP program to-
▪ Calculate length of string
<?php
// Function to calculate the length of a string
function calculateStringLength($string) {
$length = 0;
for ($i = 0; isset($string[$i]); $i++) {
$length++;
}
return $length;
}

// Example string
$inputString = "Hello world! Welcome to PHP programming.";

// Calculate length of string


$length = calculateStringLength($inputString);

// Output the length


echo "Length of the string: $length<br>";
?>
Output:

▪ Count the number of words in string without using string functions:


<?php
// Function to count the number of words in a string
function countWords($string) {
$wordCount = 0;
$inWord = false; // Flag to indicate if we are in a word

// Iterate through each character in the string


for ($i = 0; isset($string[$i]); $i++) {
if ($string[$i] != ' ' && $string[$i] != "\n" && $string[$i] != "\t") {
// If we are not in a word, start counting a new word
if (!$inWord) {
$wordCount++;
$inWord = true; // We've found a word
}
} else {
// We're in whitespace, so we're not in a word anymore
$inWord = false;
}
}

return $wordCount;
}
// Example string
$inputString = "Hello world! Welcome to PHP programming.";

// Count the number of words


$wordCount = countWords($inputString);

// Output the result


echo "Number of words in the string: $wordCount";
?>

Output:
➢ Write a simple PHP program to demonstrate use of various built-in string functions.
<?php
// Example string
$originalString = "Hello, PHP World! Welcome to PHP Programming.";

// Demonstrating built-in string functions


echo "Original String: $originalString<br>";

// 1. strlen() - Get string length


$length = strlen($originalString);
echo "Length of the string: $length<br>";

// 2. trim() - Remove whitespace from both sides


$trimmedString = trim($originalString);
echo "Trimmed String: $trimmedString<br>";

// 3. strtoupper() - Convert to uppercase


$upperString = strtoupper($trimmedString);
echo "Uppercase String: $upperString<br>";

// 4. strtolower() - Convert to lowercase


$lowerString = strtolower($upperString);
echo "Lowercase String: $lowerString<br>";

// 5. str_replace() - Replace a substring with another


$replacedString = str_replace("PHP", "Python", $originalString);
echo "Replaced String: $replacedString<br>";
// 6. substr() - Get a substring
$substring = substr($trimmedString, 7, 3); // Starting at index 7, length 3
echo "Substring (from index 7, length 3): $substring<br>";

// 7. strpos() - Find position of first occurrence of a substring


$position = strpos($trimmedString, "World");
echo "Position of 'World': $position<br>";
// 8. explode() - Split a string by a delimiter
$wordsArray = explode(" ", $trimmedString); // Split by spaces
echo "Words Array: ";
print_r($wordsArray);
echo "<br>";
// 9. implode() - Join array elements with a string
$joinedString = implode("-", $wordsArray);
echo "Joined String with hyphens: $joinedString<br>";
?>

Output:
Experiment -6
Aim:
Write a simple PHP program to demonstrate use of Simple function and Parametrized function.

Theory:
<?php
// Simple function
function sayHello() {
echo "Hello, World! <br>";
}

// Call the simple function


sayHello();

// Parameterized function
function greetUser($name) {
echo "Hello, $name! I welcome you to PHP programming.<br>";
}

// Call the parameterized function with different names


greetUser("Om");
greetUser("Sushant");
greetUser("Jaspreet");

// Parameterized function with default parameter


function calculateArea($length, $width = 5) {
$area = $length * $width;
echo "The area of a rectangle with length $length and width $width is: $area<br>";
}
// Call the function with both parameters
calculateArea(10, 7);

// Call the function with only the length parameter (width will use the default value)
calculateArea(10);
?>

Output:
Experiment -7
Aim:
Develop web page with data validation.
Theory:
<?php
// Initialize variables and error messages
$name = $email = $password = "";
$nameErr = $emailErr = $passwordErr = "";
$successMessage = "";

// Function to validate input


function test_input($data) {
return htmlspecialchars(stripslashes(trim($data)));
}

// Check if the form is submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate name
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space are allowed";
}
}

// Validate email
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

// Validate password
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
if (strlen($password) < 6) {
$passwordErr = "Password must be at least 6 characters long";
}
}

// If there are no errors, process the data


if (empty($nameErr) && empty($emailErr) && empty($passwordErr)) {
$successMessage = "Registration successful!";
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Validation Example</title>
<style>
.error { color: red; }
.success { color: green; }
</style>
</head>
<body>

<h2>Registration Form</h2>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name; ?>">
<span class="error"><?php echo $nameErr; ?></span><br><br>

Email: <input type="text" name="email" value="<?php echo $email; ?>">


<span class="error"><?php echo $emailErr; ?></span><br><br>

Password: <input type="password" name="password" value="<?php echo $password;


?>">
<span class="error"><?php echo $passwordErr; ?></span><br><br>

<input type="submit" value="Register">


</form>

<?php
if (!empty($successMessage)) {
echo "<p class='success'>$successMessage</p>";
}
?>

</body>
</html>

Output:
Experiment -8
Aim:
Write simple PHP program to-
a. Set cookies and read it.
b. Demonstrate session management

Theory:
➢ Write simple PHP program to-

• Set cookies and read it.


<?php
setcookie("user", "Om", time() + 86400, "/");

if (isset($_COOKIE["user"])) {
echo "Cookie 'user' is set!<br>";
echo "Value: " . $_COOKIE["user"];
} else {
echo "Cookie 'user' is not set.";
}
?>

Output:
➢ Write simple PHP program to-
• Demonstrate session management
<?php
session_start(); // Start the session
if (isset($_GET['action']) && $_GET['action'] == 'logout') {
// Unset all session variables
session_unset();
// Destroy the session
session_destroy();
echo "You have been logged out.<br><br>";
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['username'])) {
// Simulate a successful login by setting session variables
$_SESSION['user_id'] = 101;
$_SESSION['username'] = $_POST['username'];
}
if (isset($_SESSION['user_id']) && isset($_SESSION['username'])) {
// User is logged in, show dashboard
echo "Welcome, " . htmlspecialchars($_SESSION['username']) . "!<br>";
echo "Your User ID is: " . htmlspecialchars($_SESSION['user_id']) . "<br>";
echo '<a href="?action=logout">Logout</a>';
} else {
// User is not logged in, show login form
echo "<h2>Login</h2>";
echo '<form method="POST" action="">';
echo 'Username: <input type="text" name="username" required>';
echo '<input type="submit" value="Login">';
echo '</form>';
}
?>

Output:
Experiment -9
Aim:
Develop a simple application to-
a. Enter data into database.
b. Retrieve and present data from database.

Theory:
➢ Develop a simple application to-

• Enter data into database.


<?php
// Database connection
$database_file = "simple_app.db"; // Path to the SQLite database file
$conn = new PDO("sqlite:$database_file");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Check connection (optional)


if (!$conn) {
die("Connection failed: " . $conn->errorInfo());
}

// Create table if it does not exist


$sql = "CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL
)";
$conn->exec($sql);

// Insert data into the database


if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];

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


$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);

if ($stmt->execute()) {
echo "New record created successfully<br>";
} else {
echo "Error: " . $stmt->errorInfo()[2];
}
}
$conn = null; // Close the connection
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Enter Data</title>
</head>
<body>
<h2>Enter User Data</h2>
<form method="post" action="">
Name: <input type="text" name="name" required><br>
Email: <input type="email" name="email" required><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Output:
➢ Develop a simple application to-
• Retrieve and present data from database.
<?php
session_start(); // Start the session

// Check if the user has logged out


if (isset($_GET['action']) && $_GET['action'] == 'logout') {
// Unset all session variables
session_unset();
// Destroy the session
session_destroy();
echo "You have been logged out.<br><br>";
}

// Handle login
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['username'])) {
// Simulate a successful login by setting session variables
$_SESSION['user_id'] = 101;
$_SESSION['username'] = $_POST['username'];
}

// Check if user data exists in session


if (isset($_SESSION['user_id']) && isset($_SESSION['username'])) {
// User is logged in, show dashboard
echo "Welcome, " . htmlspecialchars($_SESSION['username']) . "!<br>";
echo "Your User ID is: " . htmlspecialchars($_SESSION['user_id']) . "<br>";
echo '<a href="?action=logout">Logout</a>';
} else {
// User is not logged in, show login form
echo "<h2>Login</h2>";
echo '<form method="POST" action="">';
echo 'Username: <input type="text" name="username" required>';
echo '<input type="submit" value="Login">';
echo '</form>';
}
?>

Output:
Experiment -10
Aim:
Develop a simple application to Update, Delete table data from database.

Theory:
<?php
// Database connection
$database_file = 'simple_app.db'; // SQLite database file path
$conn = new PDO("sqlite:$database_file");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Create the users table if it doesn't exist


$conn->exec("CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL
)");

// Handle Update operation


if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$email = $_POST['email'];

$stmt = $conn->prepare("UPDATE users SET name = :name, email = :email WHERE id =


:id");
$stmt->bindParam(":name", $name);
$stmt->bindParam(":email", $email);
$stmt->bindParam(":id", $id);
if ($stmt->execute()) {
echo "Record updated successfully.";
} else {
echo "Error updating record: " . $stmt->errorInfo()[2];
}
}

// Handle Delete operation


if (isset($_GET['delete'])) {
$id = $_GET['delete'];

$stmt = $conn->prepare("DELETE FROM users WHERE id = :id");


$stmt->bindParam(':id', $id);

if ($stmt->execute()) {
echo "Record deleted successfully.";
} else {
echo "Error deleting record: " . $stmt->errorInfo()[2];
}
}

// Retrieve data from the database


$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Manage 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 if ($result->rowCount() > 0): ?>
<?php foreach ($result as $row): ?>
<tr>
<td><?= htmlspecialchars($row['id']) ?></td>
<td><?= htmlspecialchars($row['name']) ?></td>
<td><?= htmlspecialchars($row['email']) ?></td>
<td>
<a href="?edit=<?= $row['id'] ?>">Edit</a> |
<a href="?delete=<?= $row['id'] ?>" onclick="return confirm('Are you
sure?')">Delete</a>
</td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr><td colspan="4">No records found.</td></tr>
<?php endif; ?>
</table>

<?php
// Handle Edit operation
if (isset($_GET['edit'])):
$id = $_GET['edit'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user):
?>
<h2>Edit User</h2>
<form method="post" action="">
<input type="hidden" name="id" value="<?= htmlspecialchars($user['id']) ?>">
Name: <input type="text" name="name" value="<?= htmlspecialchars($user['name'])
?>"><br>
Email: <input type="email" name="email" value="<?= htmlspecialchars($user['email'])
?>"><br>
<input type="submit" name="update" value="Update">
</form>
<?php endif; endif; ?>
</body>
</html>
<?php
$conn = null; // Close the connection
?>
Output:

You might also like