0% found this document useful (0 votes)
9 views25 pages

PHP Practicals

The document contains various PHP programming exercises covering topics such as odd/even number checking, positive/negative number identification, calendar functionality, logical operators, array usage, string manipulation, mathematical functions, inheritance, and form design. Each practical includes code snippets demonstrating the implementation of these concepts. Additionally, it showcases form validation and data handling through HTML forms with various input types.

Uploaded by

sanskrutinile06
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)
9 views25 pages

PHP Practicals

The document contains various PHP programming exercises covering topics such as odd/even number checking, positive/negative number identification, calendar functionality, logical operators, array usage, string manipulation, mathematical functions, inheritance, and form design. Each practical includes code snippets demonstrating the implementation of these concepts. Additionally, it showcases form validation and data handling through HTML forms with various input types.

Uploaded by

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

Practical2

1.Create a php program to find odd or even number from given


<?php
$a = (int)readline("Enter a number: "); // Get user input
if ($a % 2 == 0) {
echo "Given number is: EVEN"; // Use newline (\n) instead of <br>
} else {
echo "Given number is: ODD";
}
?>

2.Write a program to check no is positive or negative.


<?php
$a = (int)readline("Enter a number: "); // Get input from user
if ($a > 0) {
echo "The number is POSITIVE.\n";
} elseif ($a < 0) {
echo "The number is NEGATIVE.\n";
} else {
echo "The number is ZERO.\n";
}
?>
3.Write a calendar program using switch statement.
<?php
$month = (int)readline("Enter the month number (1-12): ");
$year = (int)readline("Enter the year: ");
switch ($month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
$days = 31;
break;
case 4:
case 6:
case 9:
case 11:
$days = 30;
break;
case 2:
if (($year % 4 == 0 && $year % 100 != 0) || ($year % 400 == 0)) {
$days = 29;
} else {
$days = 28;
}
break;
default:
echo "Invalid month entered.\n";exit;
}echo "Month $month of year $year has $days days.\n";?>

4. Write a program to make the use of logical operators.


<?php
$a = (int)readline("Enter the first number: ");
$b = (int)readline("Enter the second number: ");
if ($a > 0 && $b > 0) {
echo "Both numbers are positive.";
} elseif ($a > 0 || $b > 0) {
echo"At least one number is positive";
} else {
echo "Both numbers are non-positive.\n";
}
?>
Practical3

1.Write a program to print first 30 even numbers.


<?php
for ($i = 1; $i <= 30; $i++) {
echo $i * 2 . "\n";
}
?>
2.Write any program using if condition with for loop

<?php
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) {
echo "$i is even\n";
} else {
echo "$i is odd\n";
}
}
?>

3.Write a program to display pyramids of star/patterns using increment/decrement.

<?php
$rows = 5;
for ($i = 1; $i <= $rows; $i++) {
for ($j = $i; $j < $rows; $j++) {
echo " ";
}
$stars = 2 * $i - 1;
echo str_pad("", $stars, "*") . "\n";
}
?>
Practical4

1.Develop a program to using Indexed array.


<?php
$city = array(0 => "Pune", 1 => "Mumbai", 2 => "Delhi", 3 => "Chennai");
echo "Printing the entire array: <br>";
for ($i = 0; $i < count($city); $i++) {
echo "Index $i: " . $city[$i] . "<br>";
}
echo "<br>Alternatively, printing the array using print_r():<br>";
print_r($city);
?>

2.Develop a program to using Associative array


<?php
$city = array(
"Mumbai" => "India",
"Paris" => "France",
"London" => "England",
"New York" => "USA",
"Tokyo" => "Japan",
"Rome" => "Italy",
"Rio de Janeiro" => "Brazil");
echo "Printing the associative array:<br>";
foreach ($city as $cityName => $country) {
echo "City: $cityName, Country: $country<br>";}
echo "<br>Alternatively, printing the array using print_r():<br>";
print_r($city);
?>
3.Develop a program to using Multidimensional array.

<?php
$students = array(
"Alice" => array("Math" => 85, "Science" => 92, "English" => 88),
"Bob" => array("Math" => 78, "Science" => 81, "English" => 74),
);
echo "Student Marks Information:<br>";
foreach ($students as $studentName => $subjects) {
echo "<strong>Student: $studentName</strong><br>";
foreach ($subjects as $subject => $marks) {
echo "$subject: $marks<br>";
}
echo "<br>";
}
echo "<br>Alternatively, printing the multidimensional array using print_r():<br>";
print_r($students);
?>
Practical5

1. Write a PHP program to- i) Calculate length of string.ii)Count the number of words
in string without using string functions.
<?php
$input = "This is a sample string";
$length = 0;
for ($i = 0; isset($input[$i]); $i++) {
$length++; }
echo "Length of the string: $length<br>";
$wordCount = 0;
$inWord = false;
for ($i = 0; $i < $length; $i++) {
if ($input[$i] != ' ' && !$inWord) {
$inWord = true;
$wordCount++;
} elseif ($input[$i] == ' ') {
$inWord = false; }}
echo "Number of words in the string: $wordCount<br>";
?>

2.Write a program to demonstrate PHP maths function.


<?php
$num1 = -10.5; $num2 = 16;
echo "Input numbers: num1 = $num1, num2 = $num2<br><br>";
echo "Absolute value of num1: " . abs($num1) . "<br>";
echo "Square root of num2: " . sqrt($num2) . "<br>";
echo "Round num1 to nearest integer: " . round($num1) . "<br>";
echo "Ceiling of num1: " . ceil($num1) . "<br>";
echo "Floor of num1: " . floor($num1) . "<br>";
echo "2 raised to the power 3: " . pow(2, 3) . "<br>";
echo "Random number between 1 and 100: " . rand(1, 100) . "<br>";
$degrees = 30; $radians = deg2rad($degrees);
echo "Sine of $degrees degrees: " . sin($radians) . "<br>";
?>
Practical8

1.Write a program to implements multilevel inheritance.


<?php
class Animal {
public function eat() {
echo "Animals can eat.<br>";}}
class Mammal extends Animal {
public function walk() {
echo "Mammals can walk.<br>";}}
class Dog extends Mammal {
public function bark() {
echo "Dogs can bark.<br>"; }}
$dog = new Dog();
$dog->eat();
$dog->walk();
$dog->bark();
?>

2.Write a program to implements multiple inheritance


<?php
trait TraitA {
public function sayHello() {
echo "Hello from TraitA!<br>";}}
trait TraitB {
public function sayGoodbye() {
echo "Goodbye from TraitB!<br>";}}
class MyClass {
use TraitA, TraitB;}
$obj = new MyClass();
$obj->sayHello();
$obj->sayGoodbye();
?>
3.Write a program to demonstrate parameterized constructor.
<?php
class Person {
public $name;
public $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function displayInfo() {
echo "Name: " . $this->name . "<br>";
echo "Age: " . $this->age . "<br>";
}
}
$person1 = new Person("John", 25);
$person1->displayInfo();
$person2 = new Person("Alice", 30);
$person2->displayInfo();
?>

4.Write a program to demonstrate default constructor.


<?php
class Person {
public $name;
public $age;
public function __construct() {
$this->name = "Unknown";
$this->age = 0; }
public function displayInfo() {
echo "Name: " . $this->name . "<br>";
echo "Age: " . $this->age . "<br>"; }
}
$person1 = new Person();
$person1->displayInfo();
?>
Practical10

1.Write a program to design a registration form using textbox, radio button, checkbox
and button.
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<h2>Registration Form</h2>
<form action="pr10a.php" method="POST">
Full Name: <input type="text" id="name" name="name" required><br>
Email:<input type="email" id="email" name="email" required><br>
Gender:<input type="radio" id="male" name="gender" value="Male" required>
male
<input type="radio" id="female" name="gender" value="Female"> female<br>
Interests:<br>
<input type="checkbox" id="coding" name="interests[]" value="Coding">Coding<br>
<input type="checkbox" id="design" name="interests[]"
value="Design">Design<br>
<input type="checkbox" id="music" name="interests[]" value="Music">Music<br>
<input type="submit" value="Register">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$gender = $_POST['gender'];
$interests = isset($_POST['interests']) ? implode(", ", $_POST['interests']) :
"None";
echo "<h3>Registration Successful!</h3>";
echo "<p>Name: $name</p>";
echo "<p>Email: $email</p>";
echo "<p>Gender: $gender</p>";
echo "<p>Interests: $interests</p>";
}
?>
</body>
</html>
2.
<html >
<head>
<title>College Admission Form</title>
<script>
function validateForm() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var sscMarks = document.getElementById("sscMarks").value;
var errorMessages = "";
if (name.trim() == "") {
errorMessages += "Name is required.<br>";
}
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if (!emailPattern.test(email)) {
errorMessages += "Please enter a valid email address.<br>";
}
var phonePattern = /^[0-9]{10}$/;
if (!phonePattern.test(phone)) {
errorMessages += "Phone number should be a valid 10-digit
number.<br>";
}
if (sscMarks < 0 || sscMarks > 100 || isNaN(sscMarks)) {
errorMessages += "SSC marks should be between 0 and 100.<br>";
}
if (errorMessages !== "") {
document.getElementById("errorMessages").innerHTML = errorMessages;
return false;
}
return true;
}
</script>
</head>
<body>
<h2>College Admission Form</h2>
<form action="pr10b.php" method="POST" onsubmit="return validateForm()">
Full Name:<input type="text" id="name" name="name" placeholder="Enter your
full name" required><br>
email:<input type="email" id="email" name="email" placeholder="Enter your
email" required><br>
Phone Number: <input type="text" id="phone" name="phone" placeholder="Enter
your 10-digit phone number" required><br>
SSC Marks (Percentage): <input type="text" id="sscMarks" name="sscMarks"
placeholder="Enter your SSC marks" required><br>
<input type="submit" value="Submit">
</form>
<div id="errorMessages" style="color: red;"></div>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$sscMarks = $_POST['sscMarks'];
$errorMessages = "";
if (empty($name)) {
$errorMessages .= "Name is required.<br>";
}
$emailPattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/";
if (!preg_match($emailPattern, $email)) {
$errorMessages .= "Please enter a valid email address.<br>";
}
$phonePattern = "/^[0-9]{10}$/";
if (!preg_match($phonePattern, $phone)) {
$errorMessages .= "Phone number should be a valid 10-digit number.<br>";
}
if ($sscMarks < 0 || $sscMarks > 100 || !is_numeric($sscMarks)) {
$errorMessages .= "SSC marks should be between 0 and 100.<br>";
}
if ($errorMessages != "") {
echo "<div style='color: red;'><b>Errors:</b><br>" . $errorMessages . "</div>";
} else {
echo "<h3>Admission Successful!</h3>";
echo "<p>Name: $name</p>";
echo "<p>Email: $email</p>";
echo "<p>Phone Number: $phone</p>";
echo "<p>SSC Marks: $sscMarks</p>";
}
}
?>
</body>
</html>
Practical11

1.Write a program to design a form using list box, combo box and Hidden field box.
<html><head></head><body>
<h2>Form with List Box, Combo Box, and Hidden Field</h2>
<form action="pr11a.php" method="POST">
<label for="comboBox">Select a City:</label>
<select name="comboBox" id="comboBox">
<option value="Mumbai">Mumbai</option>
<option value="Pune">Pune</option>
<option value="Delhi">Delhi</option>
<option value="Chennai">Chennai</option></select><br><br>
<label for="listBox">Select your Hobbies (multiple):</label>
<select name="hobbies[]" id="listBox" multiple>
<option value="Reading">Reading</option>
<option value="Traveling">Traveling</option>
<option value="Cooking">Cooking</option>
<option value="Sports">Sports</option></select><br><br>
<input type="hidden" name="userId" value="12345">
<input type="submit" value="Submit"></form>
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") {
$selectedCity = $_POST['comboBox'];
$hobbies = $_POST['hobbies'];
$userId = $_POST['userId'];
echo "<h2>Form Submitted Successfully!</h2>";
echo "User ID: $userId<br>";
echo "Selected City: $selectedCity<br>";
echo "Selected Hobbies: " . implode(", ", $hobbies) . "<br>";} ?>
</body></html>
2.Write a program to design a form using list box, combo box.
<html><head></head><body>
<h2>Form with List Box and Combo Box</h2>
<form action="pr11b.php" method="POST">
<label for="comboBox">Select a Country:</label>
<select name="comboBox" id="comboBox">
<option value="India">India</option>
<option value="USA">USA</option>
<option value="Australia">Australia</option>
<option value="Canada">Canada</option></select><br><br>
<label for="listBox">Select your Hobbies (multiple):</label>
<select name="hobbies[]" id="listBox" multiple>
<option value="Reading">Reading</option>
<option value="Traveling">Traveling</option>
<option value="Cooking">Cooking</option>
<option value="Sports">Sports</option> </select> <br><br>
<input type="submit" value="Submit"></form>
<?phpif ($_SERVER["REQUEST_METHOD"] == "POST") {
$selectedCountry = $_POST['comboBox'];
$selectedHobbies = $_POST['hobbies'];
echo "<h2>Form Submitted Successfully!</h2>";
echo "Selected Country: $selectedCountry<br>";
echo "Selected Hobbies: ";
if (!empty($selectedHobbies)) {
echo implode(", ", $selectedHobbies);
} else {
echo "No hobbies selected.";
}
}
?>
</body>
</html>
Practical12

1.Write a simple PHP program to check that emails are valid.

<html>
<head>
</head>
<body>
<h2>Email Validation Form</h2>
<form method="POST">
<label for="email">Enter your email:</label>
<input type="text" id="email" name="email" required>
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST['email'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<p style='color:green;'>The email address '$email' is valid!</p>";
} else {
echo "<p style='color:red;'>The email address '$email' is not valid!</p>";
}
}
?>
</body>
</html>
Practical13

1.Write a program to create, modify and delete a cookie.


<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
if (isset($_POST['create_cookie'])) {
$message = "Cookie has been created/modified with the value: $name";
} elseif (isset($_POST['delete_cookie'])) {
setcookie('user', '', time() - 3600, "/");
$message = "Cookie has been deleted!";
}
}
$cookie_value = isset($_COOKIE['user']) ? $_COOKIE['user'] : 'Not set';
?>
<html>
<head>
</head>
<body>
<h2>Cookie Operations (Create, Modify, Delete)</h2>
<?php if (isset($message)) echo "<p><strong>$message</strong></p>"; ?>
<form method="POST">
<label for="name">Enter Name for Cookie:</label>
<input type="text" id="name" name="name" required>
<br><br>
<input type="submit" name="create_cookie" value="Create/Modify Cookie">
<input type="submit" name="delete_cookie" value="Delete Cookie">
</form>
</body>
</html>
2.Write a program to start and destroy a session.
<?php
session_start();
if (!isset($_SESSION['user'])) {
$_SESSION['user'] = "sanskruti Nile";
echo "Session started! User is: " . $_SESSION['user'] . "<br>";
} else {
echo "Session already started! User is: " . $_SESSION['user'] . "<br>";
}
if (isset($_POST['destroy_session'])) {
session_destroy();
echo "Session destroyed!";
}
?>
<html>
<head>
</head>
<body>
<form method="POST">
<input type="submit" name="destroy_session" value="Destroy Session">
</form>
</body>
</html>
Practical14

1.Write a program to send and receive mail using PHP


<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$to = "[email protected]";
$subject = "Test Email from PHP";
$message = "This is a test email sent using PHP.";
$headers = "From:[email protected] ";
if(mail($to, $subject, $message, $headers)) {
echo "Email sent successfully!";} else {
echo "Failed to send the email.";}
?>

2.Write a simple program to check that emails are valid.


<html><head></head><body>
<h2>Check Email Validity</h2>
<form method="post" action="">
Enter Email:<input type="text" name="email" id="email" required><br>
<button type="submit">Validate</button> </form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST['email'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<p style='color: green;'>The email address '$email' is valid.</p>";} else
{ echo "<p style='color: red;'>The email address '$email' is invalid.</p>"; } }
?>
</body>
</html>
Practical15

1.Develop a program to retrieve and present data from database


<html>
<head>
</head>
<body><h2>Student Records</h2>
<?php
$servername = "localhost"; $username = "root";
$password = ""; $dbname = "testdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, email, marks FROM students";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th><th>Marks</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['id'] . "
</td>
<td>" . $row['name'] . "
</td>
<td>" . $row['email'] . "
</td>
<td>" . $row['marks'] . "
</td>
</tr>";} echo "</table>";
}
else
{
echo "No records found.";
}
$conn->close();
?>
</body>
</html>
●​ Sql command
USE testdb;
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
marks INT NOT NULL);
INSERT INTO students (name, email, marks) VALUES
('sanskrutinile', '[email protected]', 85),
('mayurnile', '[email protected]', 88),
('pankajpatil', '[email protected]', 90);
2.Write a PHP code to insert data into employee table.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "empdb";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
if ($_SERVER["REQUEST_METHOD"] == "POST" &&
isset($_POST['add_employee'])) {
$name = $_POST["name"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$department = $_POST["department"];
$sql = "INSERT INTO employee (name, email, phone, department) VALUES
('$name', '$email', '$phone', '$department')";
if ($conn->query($sql) === TRUE) {
echo "New employee added successfully!<br>"; } else {
echo "Error: " . $sql . "<br>" . $conn->error;}}
if (isset($_POST['print_data'])) {
$sql = "SELECT * FROM employee";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<h2>Employee List</h2>";
echo "<table
border='1'><tr><th>ID</th><th>Name</th><th>Email</th><th>Phone</th><th>Depa
rtment</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"] . "</td><td>" . $row["name"] . "</td><td>" .
$row["email"] . "</td><td>" . $row["phone"] . "</td><td>" . $row["department"] .
"</td></tr>"; }
echo "</table>"; } else {
echo "No employee data found."; }}
$conn->close();
?>
<html><head></head><body>
<h1>Add Employee</h1>
<form method="POST" action="pr15b.php">
Name: <input type="text" name="name" required><br><br>
Email: <input type="email" name="email" required><br><br>
Phone: <input type="text" name="phone" required><br><br>
Department: <input type="text" name="department" required><br><br>
<button type="submit" name="add_employee">Add Employee</button>
</form><br><br>
<form method="POST" action="">
<button type="submit" name="print_data">Print Employee Data</button>
</form></body></html>
●​ Sql command
USE empdb;
CREATE TABLE employee (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
phone VARCHAR(15),
department VARCHAR(50));
Practical16
1. Write a PHP program to Update table data from student database.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "studentdb";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update'])) {
$id = $_POST["id"];
$name = $_POST["name"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$course = $_POST["course"];
$sql = "UPDATE students SET name='$name', email='$email', phone='$phone',
course='$course' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully!<br><br>";
}
else {
echo "Error updating record: " . $conn->error . "<br><br>";
}
}
$displayData = false;
if (isset($_POST['printData']))
{
$displayData = true;
}
if ($displayData) {
$sql = "SELECT * FROM students";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<h2>Student Records</h2>";echo "<table
border='1'><tr><th>ID</th><th>Name</th><th>Email</th><th>Phone</th><th>Cour
se</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["name"]. "</td><td>" .
$row["email"]. "</td><td>" . $row["phone"]. "</td><td>" . $row["course"]. "</td></tr>";
}
echo "</table>";
}
else
{
echo "No records found."; }
}
$conn->close();
?>
<html>
<head>
</head>
<body>
<h1>Update Student Information</h1>
<form method="POST" action="">
Student ID: <input type="text" name="id" required><br><br>
Name: <input type="text" name="name" required><br><br>
Email: <input type="email" name="email" required><br><br>
Phone: <input type="text" name="phone" required><br><br>
Course: <input type="text" name="course" required><br><br>
<button type="submit" name="update">Update Student</button>
</form>
<h1>Print Student Records</h1>
<form method="POST" action="">
<button type="submit" name="printData">Print Data</button>
</form>
</body>
</html>

You might also like