Wednesday, August 9, 2023

Q5) Demonstrate a program to perform the Insertion & updation of records using PHP Script in Student table with appropriate field.

 

<?php

$servername = "localhost"; // Change this to your server name

$username = "root"; // Change this to your database username

$password = ""; // Change this to your database password

$dbname = "dbStudents";

 

// Create a connection

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

 

// Check connection

if ($conn->connect_error) {

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

}

 

// Insertion: Process form submission to insert a new student record

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

    $rollNo = $_POST['roll_no'];

    $name = $_POST['name'];

    $age = $_POST['age'];

 

    // Insert new student record into the Student table

    $insert_sql = "INSERT INTO Student (RollNo, Name, Age) VALUES ('$rollNo', '$name', '$age')";

 

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

        echo "Record inserted successfully<br>";

    } else {

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

    }

}

 

// Updation: Process form submission to update an existing student record

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

    $rollNoToUpdate = $_POST['roll_no_to_update'];

    $newName = $_POST['new_name'];

    $newAge = $_POST['new_age'];

 

    // Update student record in the Student table

    $update_sql = "UPDATE Student SET Name = '$newName', Age = '$newAge' WHERE RollNo = '$rollNoToUpdate'";

 

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

        echo "Record updated successfully<br>";

    } else {

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

    }

}

 

// Close the connection

$conn->close();

?>

 

<!DOCTYPE html>

<html>

<head>

    <title>Student Records</title>

</head>

<body>

    <h1>Student Records</h1>

 

    <!-- Insertion Form -->

    <h2>Insert New Student Record</h2>

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

        Roll No: <input type="text" name="roll_no" required><br>

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

        Age: <input type="text" name="age" required><br>

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

    </form>

 

    <!-- Updation Form -->

    <h2>Update Student Record</h2>

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

        Roll No to Update: <input type="text" name="roll_no_to_update" required><br>

        New Name: <input type="text" name="new_name" required><br>

        New Age: <input type="text" name="new_age" required><br>

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

    </form>

</body>

</html>

No comments:

Post a Comment