PHP 4 to 10

Program 4 Read form data 

 <!DOCTYPE html>

<html>

<head>

 <title>PHP Form</title>

 <style>

 #field-container { width: 300px; margin: 50px auto; }

 input, select, textarea { width: 100%; padding: 5px; margin-top: 2px; box-sizing: border-box; }

 </style>

</head>

<body>

 <div id="field-container">

 <h2>Reading Form Data</h2>

 <?php 

 if ($_SERVER["REQUEST_METHOD"] == "POST") {

 $name = $_POST['name']; 

 $gender = $_POST['gender']; 

 $hobbies = isset($_POST['hobbies']) ? implode(', ', $_POST['hobbies']) : 'None';

 $comments = $_POST['comments']; 

 $branch = $_POST['branch'];

 echo "<h3>Submitted Data:</h3> Name: $name<br>Gender: $gender<br>Branch: 

$branch<br>Hobbies: $hobbies<br>Comments: $comments<br>";

 } else {?>

 <form action="" method="post">

 <label>Name :</label><input type="text" name="name" required><br><br>

 <label>Gender:</label><br>

 <input type="radio" name="gender" value="Male" required> Male

 <input type="radio" name="gender" value="Female" required> Female<br><br>

 <label>Branch:</label><select name="branch" required>

 <option value="Computer Science">Computer Science</option>

 <option value="Electronics">Electronics</option>

 <option value="Mechanical">Mechanical</option>

 <option value="Civil">Civil</option>

 </select><br><br>

<label>Hobbies:</label><br>

 <input type="checkbox" name="hobbies[]" value="Reading"> Reading

 <input type="checkbox" name="hobbies[]" value="Sports"> Sports

 <input type="checkbox" name="hobbies[]" value="Music"> Music<br><br>

 <label>Comments:</label><textarea name="comments" rows="3"></textarea><br><br>

 <input id="input-btn" type="submit" value="Submit">

 </form>

 <?php } ?>

 </div>

</body>

</html> 


program 5 METHOD OVERLOADING, OVERRIDING


<?php

class Shape {

 public function draw() {

 echo "Calculating the area of a generic shape.<br>";

 }

}

class CircleRectangle extends Shape {

 public function draw() {

 echo "<h2>Method Overloading and Overriding</h2>";

 echo "<h3>Calculating the area of Circle and Rectangle</h3><br>";

 }

 public function __call($name, $arguments) {

 if ($name == 'area') {

 if (count($arguments) == 1) {

 // Area of circle

 $radius = $arguments[0];

 $area = pi() * $radius * $radius;

 echo "<b>Area of circle</b> with radius $radius is $area.<br><br>";

 } elseif (count($arguments) == 2) {

 // Area of rectangle

 $length = $arguments[0];

 $width = $arguments[1];

 $area = $length * $width;

 echo "<b>Area of rectangle </b>with length $length and width $width is $area.<br><br>";

 } else {

 echo "Invalid number of arguments for area.<br><br>";

 }

 } else {

 echo "Method '$name' not found.<br><br>";

 }

 }

}

$shape = new CircleRectangle();

$shape->draw(); 

$shape->area(5); 

$shape->area(10, 4); 

$shape->area(); 

$shape->perimeter(5); 

?>


Program 6 INHERITANCE


<?php

class Employee {

 public $name;

 public $position;

 public $salary;

 public function __construct($name, $position, $salary) {

 $this->name = $name;

 $this->position = $position;

 $this->salary = $salary;

 }

 public function displayDetails() {

 echo "<b>Employee Name : </b>" . $this->name . "<br><br>";

 echo "<b>Position : </b>" . $this->position . "<br><br>";

 echo "<b>Salary : </b>" . $this->salary . "<br><br>";

 }

}

class Manager extends Employee {

 public $department;

 public function __construct($name, $position, $salary, $department) {

 parent::__construct($name, $position, $salary);

 $this->department = $department;

 }

 public function displayDetails() {

 parent::displayDetails();

 echo "<b>Department : </b>" . $this->department . "<br><br><br><br>";

 }

}

class Developer extends Employee {

 public $programmingLanguage;

 public function __construct($name, $position, $salary, $programmingLanguage) {

 parent::__construct($name, $position, $salary);

 $this->programmingLanguage = $programmingLanguage;

 }

 public function displayDetails() {

 parent::displayDetails();

 echo "<b>Programming Language : </b>" . $this->programmingLanguage . "<br><br>";

 }

}

echo "<h2>Employee Details using Inheritance</h2>";

// Create Manager object

$manager = new Manager("Raja", "Senior Manager", 80000, "Sales");

$manager->displayDetails();

// Create Developer object

$developer = new Developer("Kumar", "Software Developer", 60000, "PHP");

$developer->displayDetails();

?>


7. File handling 

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

</head>

<body>

<?php

$filename = "college.txt";

file_put_contents($filename, "Department of Computer Science.\nKGiSL Institute of Information 

Management.\n");

echo "File written successfully.<br><br>";

echo "<b>Reading file contents:</b><br>";

echo nl2br(file_get_contents($filename)); 

file_put_contents($filename, "Saravanampatti.\n", FILE_APPEND); echo "<br>Content appended 

successfully.<br><br>";

echo "<b>Updated file contents:</b><br>";

echo nl2br(file_get_contents($filename));

?>

</body>

</html>



9. IMPLEMENT COOKIES


<?php

$action = $_GET['action'] ?? '';

// Logout section

if ($action == 'logout') {

 setcookie('username', '', 

time() - 3600, '/');

 header("Location: 

program9.php");

 exit();

}

// Login form submission

if 

($_SERVER['REQUEST_ME

THOD'] == 'POST') {

 $username = 

trim($_POST['username']);

 if (!empty($username)) {

 setcookie('username', 

$username, time() + 3600, '/'); 

// valid for 1 hour

 header("Location: 

program9.php");

 exit();

 } else {

 $error = "Please enter a 

username.";

 }

}

// If cookie exists, show

welcome message

if

(isset($_COOKIE['username'])

) {

 $username =

htmlspecialchars($_COOKIE['

username']);

 echo "<h2>Welcome,

$username!</h2>";

 echo "<p>Cookie is set and

you are logged in.</p>";

 echo "<a

href='?action=logout'>Logout<

/a>";

 exit();

}

?>

<!DOCTYPE html>

<html>

<head>

 <title>Cookies</title>

</head>

<body>

 <h2>Login Form</h2>

 <?php if (!empty($error))

echo "<p

style='color:red;'>$error</p>";

?>

 <form method="post"

action="">

 <label>Enter

Username:</label>

<input type="text"

name="username" required>

 <input type="submit"

value="Login">

 </form>

</body>

</html>


10. DRAWING IMAGE ON A webpage



<?php

$width = 400;

$height = 600;

$image = imagecreatetruecolor($width, $height);

$background_color = imagecolorallocate($image,0, 0, 255);

$image_body_color = imagecolorallocate($image, 255, 165, 0);

$window_color = imagecolorallocate($image, 100, 200, 255);

$flame_color = imagecolorallocate($image, 255, 0, 0);

$triangle_color = imagecolorallocate($image, 0, 255, 0);

$square_color = imagecolorallocate($image, 255, 255, 255);

imagefill($image, 0, 0, $background_color);

imagefilledpolygon($image, array(

 150, 200,

 200, 90,

 250, 200

), 3, $flame_color);

imagefilledrectangle($image, 150, 201, 250, 400, $image_body_color);

imagefilledellipse($image, 200 , 250, 40, 40, $window_color);

imagefilledrectangle($image, 190, 240, 210, 260, $square_color );

imagefilledellipse($image, 200 , 350, 40, 40, $window_color);

imagefilledrectangle($image, 190, 340, 210, 360, $square_color );

imagefilledpolygon($image, array(250, 380, 350, 380, 250, 300 ), 3, $triangle_color);

imagefilledpolygon($image, array(60, 380, 150, 380, 150, 300 ),3, $triangle_color);

imagefilledpolygon($image, array(150, 430,170, 400,190, 430), 3, $triangle_color);

imagefilledpolygon($image, array(210, 430,230, 400,250, 430), 3, $triangle_color);

header("Content-Type: image/png");

imagepng($image);

imagedestroy($image);

?>


8 .CRUD Operations

<?php

$servername = "localhost";

$username = "root";

$password = "";

$database = "student";

$conn = mysqli_connect($servername, $username, $password, $database);

if (!$conn) {

 die("Connection failed: " . mysqli_connect_error());

}

// Insert Record

if (isset($_POST["submit1"])) {

 // Check that all required fields are filled

 if (!empty($_POST["StudentName"]) && !empty($_POST["StudentId"]) &&

!empty($_POST["Department"]) && !empty($_POST["Year"])) {

 $studentId = $_POST["StudentId"];

 $studentName = $_POST["StudentName"];

 $department = $_POST["Department"];

 $year = $_POST["Year"];

 // Check if the Student ID already exists

 $checkQuery = "SELECT * FROM studentdetails WHERE StudentId = '$studentId'";

 $checkResult = mysqli_query($conn, $checkQuery);

 if (mysqli_num_rows($checkResult) > 0) {

 echo "<b style='color:red;'> Student ID '$studentId' already exists. </b><br>";

 } else {

 // If not exists, insert new record

 $insertQuery = "INSERT INTO studentdetails (StudentName, StudentId, Department, Year)

 VALUES ('$studentName', '$studentId', '$department', '$year')";

if (mysqli_query($conn, $insertQuery)) {

 echo "<b style='color:green;'>Record inserted successfully.</b><br>";

 } else {

 echo "Error inserting record: " . mysqli_error($conn) . "<br>";

 }

 }

 } else {

 echo "All fields are required for insertion.<br>";

 }

}

// Update Record

if (isset($_POST["submit4"])) {

 $name = $_POST["StudentName"];

 $id = $_POST["StudentId"];

 $dept = $_POST["Department"];

 $year = $_POST["Year"];

 if (!empty($id_to_update) && !empty($new_firstname) && !empty($new_lastname) &&

!empty($new_age)) {

 $sql = "UPDATE studentdetails

 SET StudentName='$name', Department='$dept', Year='$year'

 WHERE StudentId='$id'";

 $result = mysqli_query($conn, $sql);

 if ($result) {

 if (mysqli_affected_rows($conn) > 0) {

 echo "<p style='color:green;'>Record updated successfully for Student ID: $id.</p>";

 } else {

 echo "<p style='color:red;'>No record found with Student ID: $id.</p>";

 }

 } else {

 echo "<p style='color:red;'>Error updating record: " . mysqli_error($conn) . "</p>";

}

 } else {

 echo "<p style='color:red;'>All Fields are required for update.</p>";

 }

}

// Delete Record

if (isset($_POST["submit2"])) {

 $studentId = $_POST["StudentId"];

 if (empty($studentId)) {

 echo "<p style='color:red;'>Student ID is required for deletion.</p>";

 } else {

 $sql = "DELETE FROM studentdetails WHERE StudentId='$studentId'";

 $result = mysqli_query($conn, $sql);

 if ($result) {

 if (mysqli_affected_rows($conn) > 0) {

 echo "<p style='color:green;'>Record deleted successfully.</p>";

 } else {

 echo "<p style='color:red;'>No record found with Student ID: $studentId.</p>";

 }

 } else {

 echo "<p style='color:red;'>Error deleting record: " . mysqli_error($conn) . "</p>";

 }

 }

}

// Display Records

if (isset($_POST["submit3"])) {

 $sql = "SELECT * FROM studentdetails ORDER BY StudentId ASC";

 $res = mysqli_query($conn, $sql);

 if (mysqli_num_rows($res) > 0) {

echo "<center><h2>Student Records</h2>";

 echo "<table border='1' cellspacing='0' cellpadding='8'>";

 echo "<tr style='background-color:#f2f2f2;'>

 <th>Student Name</th>

 <th>Student ID</th>

 <th>Department</th>

 <th>Year</th>

 </tr>";

 while ($row = mysqli_fetch_assoc($res)) {

 echo "<tr>

 <td>" . $row["StudentName"] . "</td>

 <td>" . $row["StudentId"] . "</td>

 <td>" . $row["Department"] . "</td>

 <td>" . $row["Year"] . "</td>

 </tr>";

 }

 echo "</table></center>";

 } else {

 echo "<p style='color:red;'>No records found in the database.</p>";

 }

}

mysqli_close($conn);

?>

<html>

<head>

 <title>Student Database Management</title>

</head>

<body>

<center>

 <h1>STUDENT DETAILS MANAGEMENT</h1>

<form method="post" action="">

 <table>

 <tr>

 <td>Student Name</td>

 <td><input type="text" name="StudentName"></td>

 </tr>

 <tr>

 <td>Student ID</td>

 <td><input type="text" name="StudentId"></td>

 </tr>

 <tr>

 <td>Department</td>

 <td><input type="text" name="Department"></td>

 </tr>

 <tr>

 <td>Year</td>

 <td><input type="text" name="Year"></td>

 </tr>

 <tr>

 <td colspan="2" align="center">

 <input type="submit" name="submit1" value="INSERT">

 <input type="submit" name="submit4" value="UPDATE">

 <input type="submit" name="submit2" value="DELETE">

 <input type="submit" name="submit3" value="DISPLAY">

 </td>

 </tr>

 </table>

 </form>

</center>

</body>

</html>

Crud Operations

<?php

$server = "localhost";

$port = "3306";

$user = "root";

$pass = "";

$db = "students";


// Connect to MySQL (without DB first)

$conn = mysqli_connect($server, $user, $pass, "", $port);

if (!$conn) {

    die("❌ Not connected to MySQL");

} else {

    echo "✅ Connected successfully<br>";

}


// Create database if not exists

$query = "CREATE DATABASE IF NOT EXISTS $db";

if (mysqli_query($conn, $query)) {

    echo "✅ Database '$db' created successfully<br>";

}


// Connect with database

$con = mysqli_connect($server, $user, $pass, $db);


// Create table if not exists

$cquery = "CREATE TABLE IF NOT EXISTS student(

    id INT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(20),

    age INT,

    department VARCHAR(20)

)";

if (mysqli_query($con, $cquery)) {

    echo "✅ Table 'student' ready<br><br>";

} else {

    echo "❌ Table creation failed: " . mysqli_error($con);

}


// INSERT

if (isset($_POST['insert'])) {

    $name = $_POST['name'];

    $age = $_POST['age'];

    $depart = $_POST['depart'];

    $iquery = "INSERT INTO student(name, age, department) VALUES('$name', $age, '$depart')";

    mysqli_query($con, $iquery);

    echo "✅ Record inserted<br>";

}


// UPDATE

if (isset($_POST['update'])) {

    $id = $_POST['id'];

    $name = $_POST['name'];

    $age = $_POST['age'];

    $department = $_POST['depart'];


    $uquery = "UPDATE student SET name='$name', age=$age, department='$department' WHERE id=$id";

    mysqli_query($con, $uquery);

    echo "✅ Record updated<br>";

}


// DELETE

if (isset($_POST['delete'])) {

    $id = $_POST['id'];

    $dquery = "DELETE FROM student WHERE id=$id";

    mysqli_query($con, $dquery);

    echo "✅ Record deleted<br>";

}


// Display table

$squery = "SELECT * FROM student";

$results = mysqli_query($con, $squery);


echo "<table border='2' cellpadding='5'>

<tr><th>ID</th><th>Name</th><th>Age</th><th>Department</th></tr>";


foreach ($results as $result) {

    echo "<tr>";

    echo "<td>" . $result['id'] . "</td>";

    echo "<td>" . $result['name'] . "</td>";

    echo "<td>" . $result['age'] . "</td>";

    echo "<td>" . $result['department'] . "</td>";

    echo "</tr>";

}

echo "</table>";


mysqli_close($con);

?>


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Student CRUD</title>

</head>

<body>

    <h2>Student Data Form</h2>

    <form method="POST">

        <label for="id">ID</label>

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


        <label for="name">Name</label>

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


        <label for="age">Age</label>

        <input type="text" name="age" id="age"><br><br>


        <label for="depart">Department</label>

        <input type="text" name="depart" id="depart"><br><br>


        <input type="submit" value="Insert" name="insert">

        <input type="submit" value="Update" name="update">

        <input type="submit" value="Delete" name="delete">

        <input type="reset" value="Reset">

    </form>

</body>

</html>

Comments

Popular posts from this blog

PHP

2,4