Wednesday, December 20, 2023

AL/ML

Command to open jupiter

python  -m jupyter lab


Read the file

 import pandas as pd

# Specify the path to your CSV file

csv_file_path = 'path/to/your/file.csv'


# Read the CSV file into a DataFrame

df = pd.read_csv(csv_file_path)


# Display the DataFrame

print(df)


# Display the first 5 rows of the DataFrame
print(df.head())

# Display specific columns
print(df[['Column1', 'Column2']])

------------------------------------------------------------------------------------------
#install
pip install pandas
----------------------------------------------------------------------------

histogram

import matplotlib.pyplot as plt
import pandas as pd

# Specify the path to your CSV file
csv_file_path = 'manish.csv'

# Read the CSV file into a DataFrame
df = pd.read_csv(csv_file_path)

# Choose the column for which you want to create a histogram
selected_column = 'Number of employees'

# Create a histogram
plt.hist(df[selected_column], bins=10, color='blue', edgecolor='black')

# Customize the plot
plt.title('Histogram of {}'.format(selected_column))
plt.xlabel(selected_column)
plt.ylabel('Frequency')

# Show the plot
plt.show()
---------------------------------------------------------------------------------------------------------------
DATA CLEANINIG

    import pandas as pd

# Specify the path to your CSV file
csv_file_path = 'manish.csv'

# Read the CSV file into a DataFrame
df = pd.read_csv(csv_file_path)

# Check for missing values
print(df.isnull().sum())

# Drop rows with missing values
df_cleaned = df.dropna()

# Alternatively, fill missing values with a specific value
# df_cleaned = df.fillna(value)
df_cleaned = df.drop_duplicates()

Monday, December 18, 2023

Demonstrate WebView to display the web pages in an android application.

 activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">



    <WebView

        android:id="@+id/web"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        tools:layout_editor_absoluteX="8dp"

        tools:layout_editor_absoluteY="8dp" />

</RelativeLayout>


activity.java

import androidx.appcompat.app.AppCompatActivity;

import android.webkit.WebView;

import android.webkit.WebViewClient;

import android.os.Bundle;


public class MainActivity extends AppCompatActivity {


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        WebView webView = findViewById(R.id.web);


        webView.loadUrl("https://www.geeksforgeeks.org/how-to-use-webview-in-android/");


        webView.getSettings().setJavaScriptEnabled(true);

         webView.setWebViewClient(new WebViewClient());

    }


}

Q:- Write an android code to turn ON/OFF the Wi-Fi

 activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:layout_margin="16dp"

    android:gravity="center"

    android:orientation="vertical">


    <ToggleButton

        android:id="@+id/toggleButton"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:checked="false"

        />


    <TextView

        android:id="@+id/textView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginTop="16dp"

        />


</LinearLayout>


activity.java


import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;

import android.net.wifi.WifiManager;

import android.os.Bundle;

import android.widget.CompoundButton;

import android.widget.TextView;

import android.widget.ToggleButton;



public class MainActivity extends AppCompatActivity {


    ToggleButton toggleButton;

    TextView textView;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        toggleButton = (ToggleButton) findViewById(R.id.toggleButton);

        textView = (TextView) findViewById(R.id.textView);


       

        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override

            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {

                if (checked) {

                    textView.setText("WiFi is ON");

                    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

                    wifi.setWifiEnabled(true);

                } else {

                    textView.setText("WiFi is OFF");

                    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

                    wifi.setWifiEnabled(false);

                }

            }

        });


        if (toggleButton.isChecked()) {

            textView.setText("WiFi is ON");

            WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

            wifi.setWifiEnabled(true);

        } else {

            textView.setText("WiFi is OFF");

            WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

            wifi.setWifiEnabled(false);

        }

    }


    }

Q:-Demonstrate Array Adapter using List View to display list of fruits.

 activity.xml

<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">


    <ListView

        android:id="@+id/simpleListView"

        android:layout_width="match_parent"

        android:layout_height="wrap_content" />


</RelativeLayout>


activity.java

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.ListView;

import android.widget.ArrayAdapter;

public class MainActivity extends AppCompatActivity {

        ListView simpleListView;


        // array objects

        String fruit[] = {"Apple", "Banana", "Mango", "strawberry"};


        @Override

        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);


            simpleListView = (ListView) findViewById(R.id.simpleListView);


            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,

                    R.layout.item_view, R.id.itemTextView, fruit);

            simpleListView.setAdapter(arrayAdapter);

        }

    }

fruits,xml

<LinearLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical">


    <TextView

        android:id="@+id/itemTextView"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_gravity="center" />


</LinearLayout>

write an application to demonstrate Alert Dialog Box in android

 activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">


    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginTop="180dp"

        android:gravity="center_horizontal"

        android:text="Press The Back Button of Your Phone."

        android:textSize="30dp"

        android:textStyle="bold" />


</RelativeLayout>


activity.java

import androidx.appcompat.app.AppCompatActivity;

import androidx.appcompat.app.AlertDialog;

import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;


import android.os.Bundle;


public class MainActivity extends AppCompatActivity {


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    }


    @Override

    public void onBackPressed() {

        // Create the object of AlertDialog Builder class

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);


        // Set the message show for the Alert time

        builder.setMessage("Do you want to exit ?");


        // Set Alert Title

        builder.setTitle("Alert !");


        // Set Cancelable false for when the user clicks on the outside the Dialog Box then it will remain show

        builder.setCancelable(false);


        // Set the positive button with yes name Lambda OnClickListener method is use of DialogInterface interface.

        builder.setPositiveButton("Yes", (DialogInterface.OnClickListener) (dialog, which) -> {

            // When the user click yes button then app will close

            finish();

        });


        // Set the Negative button with No name Lambda OnClickListener method is use of DialogInterface interface.

        builder.setNegativeButton("No", (DialogInterface.OnClickListener) (dialog, which) -> {

            // If user click no then dialog box is canceled.

            dialog.cancel();

        });


        // Create the Alert dialog

        AlertDialog alertDialog = builder.create();

        // Show the Alert Dialog box

        alertDialog.show();

    }

}



Design android application for login activity. Write android code to check login credentials with username = "mca" and password = "android". Display appropriate toast message to the user

 activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent">



    <EditText

        android:id="@+id/usernameEditText"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginTop="50dp"

        android:hint="Username"

        android:inputType="textEmailAddress" />


    <EditText

        android:id="@+id/passwordEditText"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_below="@id/usernameEditText"

        android:layout_marginTop="16dp"

        android:hint="Password"

        android:inputType="textPassword" />


    <Button

        android:id="@+id/loginButton"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@id/passwordEditText"

        android:layout_marginTop="24dp"

        android:text="Login" />

</RelativeLayout>


activitymain.java

import androidx.appcompat.app.AppCompatActivity;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import android.os.Bundle;


public class MainActivity extends AppCompatActivity {

    private EditText usernameEditText, passwordEditText;

    private Button loginButton;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        usernameEditText = findViewById(R.id.usernameEditText);

        passwordEditText = findViewById(R.id.passwordEditText);

        loginButton = findViewById(R.id.loginButton);


        loginButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                performLogin();

            }

        });

    }


    private void performLogin() {

        String enteredUsername = usernameEditText.getText().toString().trim();

        String enteredPassword = passwordEditText.getText().toString().trim();


        // Check login credentials

        if (enteredUsername.equals("mca") && enteredPassword.equals("android")) {

            // Successful login

            showToast("Login successful!");

        } else {

            // Incorrect credentials

            showToast("Incorrect username or password. Please try again.");

        }

    }


    private void showToast(String message) {

        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

    }}


Q.8) write a android program to used View.

 activity.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent">


    <com.example.customview.customview

        android:id="@+id/customview"

        android:layout_width="match_parent"

        android:layout_height="match_parent" />


</RelativeLayout>


customview.java

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.util.AttributeSet;

import android.view.View;


public class customview extends View {


    private Paint paint;


    public customview(Context context) {

        super(context);

        init();

    }


    public customview(Context context, AttributeSet attrs) {

        super(context, attrs);

        init();

    }


    private void init() {

        paint = new Paint();

        paint.setColor(Color.BLUE);

        paint.setStyle(Paint.Style.FILL);

    }


    @Override

    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);


        // Draw a colored rectangle

        canvas.drawRect(100, 100, getWidth() - 100, getHeight() - 100, paint);

    }

}


Q.4) Write android program to check the number is prime or not

activity.xml 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent">


    <EditText

        android:id="@+id/inputNumberEditText"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="Enter a number"

        android:inputType="number" />


    <Button

        android:id="@+id/checkPrimeButton"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@id/inputNumberEditText"

        android:layout_marginTop="16dp"

        android:text="Check Prime" />


    <TextView

        android:id="@+id/resultTextView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@id/checkPrimeButton"

        android:layout_marginTop="16dp"

        android:text="" />

</RelativeLayout>


activity.java

import androidx.appcompat.app.AppCompatActivity;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.os.Bundle;


public class MainActivity extends AppCompatActivity {


    private EditText inputNumberEditText;

    private Button checkPrimeButton;

    private TextView resultTextView;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        inputNumberEditText = findViewById(R.id.inputNumberEditText);

        checkPrimeButton = findViewById(R.id.checkPrimeButton);

        resultTextView = findViewById(R.id.resultTextView);


        checkPrimeButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                checkPrime();

            }

        });

    }

    private void checkPrime() {

        String inputNumberStr = inputNumberEditText.getText().toString().trim();


        if (!inputNumberStr.isEmpty()) {

            int number = Integer.parseInt(inputNumberStr);

            boolean isPrime = isPrime(number);


            if (isPrime) {

                resultTextView.setText(number + " is a prime number.");

            } else {

                resultTextView.setText(number + " is not a prime number.");

            }

        } else {

            resultTextView.setText("Please enter a number.");

        }

    }


    private boolean isPrime(int number) {

        if (number <= 1) {

            return false;

        }


        for (int i = 2; i <= Math.sqrt(number); i++) {

            if (number % i == 0) {

                return false; // Found a divisor, not a prime number

            }

        }


        return true; // No divisors found, it's a prime number

    }


}

Wednesday, August 9, 2023

Q1)Given a file called myfile.txt which contains the text: “Python is object oriented programming language”. Write a program in Python that transforms the content of the file by writing each word in a separate line.

 # Read the content from the file

with open("myfile.txt", "r") as file:

    content = file.read()

 

# Split the content into words

words = content.split()

 

# Write each word in a separate line to a new file

with open("transformed_file.txt", "w") as new_file:

    for word in words:

        new_file.write(word + "\n")

 

print("Content transformed and saved to transformed_file.txt")

10) Write a Menu Driver Program to add, display, search, sort and exit in book database containing Book_id, Book_name, Book_author through Python-MongoDB connectivity.

from pymongo import MongoClient

import pprint

 

# Connect to MongoDB

client = MongoClient("mongodb://localhost:27017/")

db = client["BookDatabase"]

collection = db["Books"]

 

def add_book():

    book_id = input("Enter Book ID: ")

    book_name = input("Enter Book Name: ")

    book_author = input("Enter Book Author: ")

   

    book_data = {

        "Book_id": book_id,

        "Book_name": book_name,

        "Book_author": book_author

    }

   

    result = collection.insert_one(book_data)

    print("Book added with ID:", result.inserted_id)

 

def display_books():

    books = collection.find()

    print("\nBooks in the database:")

    for book in books:

        pprint.pprint(book)

 

def search_book():

    book_name = input("Enter Book Name to search: ")

    query = {"Book_name": book_name}

    book = collection.find_one(query)

    if book:

        pprint.pprint(book)

    else:

        print("Book not found")

 

def sort_books():

    sort_key = input("Enter Sort Key (Book_id, Book_name, Book_author): ")

    books = collection.find().sort(sort_key)

    print("\nSorted Books:")

    for book in books:

        pprint.pprint(book)

 

  

Q9) Write a python program to validate the URL by using regular expression.

import re

 

def validate_url(url):

    pattern = r'^(http|https)://([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,6})(/[a-zA-Z0-9.-]*)*([?][a-zA-Z0-9.-]*)*$'

    if re.match(pattern, url):

        return True

    else:

        return False

 

# Test the program

url_to_validate = input("Enter a URL: ")

 

if validate_url(url_to_validate):

    print("Valid URL")

else:

    print("Invalid URL")

Q8) Write a Python program to generate a random alphabetical character, alphabetical string and alphabetical string of a fixed length. Use random.choice().

import random

import string

 

def generate_random_alphabetical_character():

    return random.choice(string.ascii_letters)

 

def generate_random_alphabetical_string(length):

    return ''.join(random.choice(string.ascii_letters) for _ in range(length))

 

def generate_fixed_length_alphabetical_string(length):

    return ''.join(random.choice(string.ascii_lowercase) for _ in range(length))

 

random_char = generate_random_alphabetical_character()

print("Random Alphabetical Character:", random_char)

 

random_string = generate_random_alphabetical_string(10)

print("Random Alphabetical String:", random_string)

 

fixed_length_string = generate_fixed_length_alphabetical_string(8)

print("Fixed Length Alphabetical String:", fixed_length_string)

Q7) 7. Write a Menu Driver Program to add, display, update, delete and exit in a student database containing Student_id,Student_name,Course through Python-MongoDB connectivity

from pymongo import MongoClient

 

# Connect to MongoDB

client = MongoClient("mongodb://localhost:27017/")

db = client["StudentDatabase"]

collection = db["Students"]

 

def add_student():

    student_id = input("Enter Student ID: ")

    student_name = input("Enter Student Name: ")

    course = input("Enter Course: ")

   

    student_data = {

        "Student_id": student_id,

        "Student_name": student_name,

        "Course": course

    }

   

    result = collection.insert_one(student_data)

    print("Student added with ID:", result.inserted_id)

 

def display_students():

    students = collection.find()

    for student in students:

        print("Student ID:", student["Student_id"])

        print("Student Name:", student["Student_name"])

        print("Course:", student["Course"])

        print("-" * 20)

 

def update_student():

    student_id = input("Enter Student ID to update: ")

    new_course = input("Enter new Course: ")

   

    result = collection.update_one({"Student_id": student_id}, {"$set": {"Course": new_course}})

    if result.modified_count > 0:

        print("Student record updated successfully")

    else:

        print("No student found with the given ID")

 

def delete_student():

    student_id = input("Enter Student ID to delete: ")

   

    result = collection.delete_one({"Student_id": student_id})

    if result.deleted_count > 0:

        print("Student record deleted successfully")

    else:

        print("No student found with the given ID")

 

while True:

    print("\nMenu:")

    print("1. Add Student")

    print("2. Display Students")

    print("3. Update Student")

    print("4. Delete Student")

    print("5. Exit")

   

    choice = input("Enter your choice: ")

   

    if choice == "1":

        add_student()

    elif choice == "2":

        display_students()

    elif choice == "3":

        update_student()

    elif choice == "4":

        delete_student()

    elif choice == "5":

        print("Exiting program")

        break

    else:

        print("Invalid choice. Please select again.")


Q6) Write a Python multithreading program to print the thread name and corresponding process for each task (assume that there are four tasks).

import threading

 

def task(task_number):

    print(f"Task {task_number} in thread {threading.current_thread().name}")

 

def main():

    tasks = 4

   

    threads = []

    for i in range(tasks):

        thread = threading.Thread(target=task, args=(i+1,))

        threads.append(thread)

        thread.start()

   

    for thread in threads:

        thread.join()

   

    print("All tasks are completed")

 

if __name__ == "__main__":

    main()

 

Q5) Plot the following data on a line chart and customize the chart according to the below-given instructions:

import matplotlib.pyplot as plt

 

# Data

months = ["January", "February", "March", "April", "May"]

sales = [510, 350, 475, 580, 600]

 

# Create a line chart

plt.figure(figsize=(10, 6))  # Set the figure size

plt.plot(months, sales, color='blue', linestyle='--', marker='D', label='Sales')  # Line style, marker, and label

 

# Title and labels

plt.title("The Monthly Sales Report")

plt.xlabel("Month")

plt.ylabel("Sales")

 

# Legends

plt.legend()

 

# Show the plot

plt.show()

 

Q4)Write a Python multithreading program which creates two threads, one for calculating the square of a given number and other for calculating the cube of a given number.

import threading

 

def calculate_square(number):

    square = number * number

    print(f"Square of {number} is {square}")

 

def calculate_cube(number):

    cube = number * number * number

    print(f"Cube of {number} is {cube}")

 

def main():

    number = int(input("Enter a number: "))

   

    thread_square = threading.Thread(target=calculate_square, args=(number,))

    thread_cube = threading.Thread(target=calculate_cube, args=(number,))

   

    thread_square.start()

    thread_cube.start()

   

    thread_square.join()

    thread_cube.join()

   

    print("Both threads have finished")

 

if __name__ == "__main__":

    main()

Q3)Create the following DataFrame Sales containing year wise sales figures for five salespersons in INR. Use the years as column labels, and salesperson names as row labels.

import pandas as pd

 

# Create the DataFrame

data = {

    2018: [110, 130, 115, 118],

    2019: [205, 165, 206, 198],

    2020: [177, 175, 157, 183],

    2021: [189, 190, 179, 169]

}

 

salespersons = ["Kapil", "Kamini", "Shikhar", "Mohini"]

 

sales_df = pd.DataFrame(data, index=salespersons)

 

# Display row labels

print("Row Labels:")

print(sales_df.index)

 

# Display column labels

print("\nColumn Labels:")

print(sales_df.columns)

 

# Display data types of each column

print("\nData Types:")

print(sales_df.dtypes)

Q2 :- Write a python program to validate an email address by using regular expression.

import re

 

def validate_email(email):

    pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'

    if re.match(pattern, email):

        return True

    else:

        return False

 

# Test the program

email_to_validate = input("Enter an email address: ")

 

if validate_email(email_to_validate):

    print("Valid email address")

else:

    print("Invalid email address")

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>

Q4) • Demonstrate a PHP Program to update a Dept of employee of given Empno from Employee table (create database dbEMP with appropriate field). Accept roll number and name from the user.

 

<?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 = "dbEMP";

 

// Create a connection

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

 

// Check connection

if ($conn->connect_error) {

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

}

 

// Process form submission

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

    $empno = $_POST['empno'];

    $newDept = $_POST['new_dept'];

 

    // Update department for the given Empno

    $sql = "UPDATE Employee SET Dept = '$newDept' WHERE Empno = '$empno'";

 

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

        echo "Department updated successfully<br>";

    } else {

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

    }

}

 

// Close the connection

$conn->close();

?>

 

<!DOCTYPE html>

<html>

<head>

    <title>Update Employee Department</title>

</head>

<body>

    <h1>Update Employee Department</h1>

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

        <label for="empno">Employee Number (Empno):</label>

        <input type="text" name="empno" required><br>

 

        <label for="new_dept">New Department:</label>

        <input type="text" name="new_dept" required><br>

 

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

    </form>

</body>

</html>