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

Webtech Practical

The document outlines a list of programming experiments, primarily focused on creating user interfaces and handling user input using various programming languages such as PHP and Python. Each experiment includes specific tasks such as creating forms, validating input, and displaying data from databases. The document also provides code snippets and explanations for implementing these tasks in a web environment.

Uploaded by

surykant4102
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Webtech Practical

The document outlines a list of programming experiments, primarily focused on creating user interfaces and handling user input using various programming languages such as PHP and Python. Each experiment includes specific tasks such as creating forms, validating input, and displaying data from databases. The document also provides code snippets and explanations for implementing these tasks in a web environment.

Uploaded by

surykant4102
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

List of Experiment

S.No. Content

1. Write a program containing the following


controls.
2. Write a program to get a user input such as
boiling point of water and test it to the appropriate
value used compare validator.
3. Create a table which has fields Eno, E name and
E sal. All of these being retrieved from the Emps
table each of the above is displayed as a drop
down list containing all the values of the
corresponding coloum in the
table.
4. Bind a checkbox list to the P name field of the
product table in the
master database so that all the name of the
product are displayed as a series of checkboxes.
5. Create a user control that display current
date/time . Include it in a web form and refresh it
each time a button is clicked.
6. Create a user control that contains a list of colors
Add a button to the web form and refresh it each
time a button is clicked.
7. Create a user control that contain a list of color.
Add a button to
the web form which when clicked changes the
color of the form to the color selected form the
list.
Write a simple PHP page that will display some
8. information onto webpage?
9. Write a php script for the following design a form
to accept a string. Write a function to count the
total number of Vowels (a,e,i,o,u) from the string
show the occurrences of each vowel
from the string.
10. Write a php script for the following design a form
to accept two number from the user. Give options
to choose the arithmetic operation (use radio
buttons.) display the result on the next form?

1
EXPERIMENT NO. 1 .
Write a program containing the following controls

1. two lable
2. atext box,
3. a button

one of the lable display adjacent to the text box displaying the messages Enterthe Experiment No. uantitywh
Ans:- import tkinter as tk

# Function to be executed when the button is clickeddef button_click():


input_text = entry.get()
label2.config(text="You entered: " + input_text)

# Create the main windowroot = tk.Tk()


root.title("Label, Text Box, and Button Example")

# Create and configure the labels


label1 = tk.Label(root, text="Enter something:")label1.pack()

label2 = tk.Label(root, text="")label2.pack()

# Create and configure the text boxentry = tk.Entry(root)


entry.pack()
# Create and configure the button
button = tk.Button(root, text="Submit", command=button_click)button.pack()

# Start the main event looproot.mainloop()

2
EXPERIMENT NO. 2.

Write a program to get a user input such as boiling point of water andtest it to the appropriate value
used compare validator.
Ans:- # Get user input for boiling point of water
user_input = input("Enter the boiling point of water (in Celsius): ")

try:
# Convert user input to a float user_boiling_point = float(user_input)

# Define the known boiling point of waterboiling_point_water_celsius = 100


boiling_point_water_fahrenheit = 212

# Check if the user input is within an acceptable rangeif (


user_boiling_point>= boiling_point_water_celsius - 0.1
and user_boiling_point<= boiling_point_water_celsius + 0.1
):

elif (
print("Your input is approximately correct (in Celsius).")

user_boiling_point>= boiling_point_water_fahrenheit - 0.1


and user_boiling_point<= boiling_point_water_fahrenheit + 0.1

):
print("Your input is approximately correct (in Fahrenheit).")
else:
print("Your input is not correct.")
except ValueError:
pri

3
EXPERIMENT NO. 3.

Create a table which has fields Eno, Ename and Esal. All of these beingretrieved from the Emps
table each of the above is displayed as a drop downlist containing all the values of the corresponding
coloumns in the table.
Ans :- Create a Database Connection:
First, create a PHP script to establish a connection to your MySEXPERIMENT NO. L database. You'llneed
to replace the placeholders with your actual database credentials.
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

// Create a connection
$conn = new mysExperiment No. li($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Retrieve Data from the Database:
Fetch the product names ("Pname") from the "Product" table in your database.
<?php
// Fetch product names from the database
$sExperiment No. l = "SELECT Pname FROM Product";
$result = $conn->Experiment No. uery($sExperiment No. l);
$productNames = array();

if ($result->num_rows> 0) {
while ($row = $result->fetch_assoc()) {
$productNames[] = $row["Pname"];
}
}
?>
Create the Checkbox List:

Use PHP to generate HTML code for the checkbox list based on the retrievedproduct names.
<?php
echo "<form method='post'>";
4
foreach ($productNames as $productName) {
echo "<input type='checkbox' name='products[]' value='$productName'>

$productName<br>";
}
echo "<input type='submit' name='submit' value='Submit'>";echo "</form>";
?>
Handle Form Submission:

Handle the form submission to process the selected products.


<?php
if (isset($_POST['submit'])) {
if (isset($_POST['products']) && !empty($_POST['products'])) {
echo "Selected products:<br>";
foreach ($_POST['products'] as $selectedProduct) {echo $selectedProduct . "<br>";
}
} else {
echo "No products selected.";
}
}
?>
Close the Database Connection:

Don't forget to close the database connection when you're done.


<?php
// Close the database connection
$conn->close();
?>
```

5
EXPERIMENT NO. 4.

Bind a checkbox list to the Pname field of the product table in the masterdatabase so that all the name
of the product are displayed as a series of checkboxes.
Ans:- import tkinter as tkimport sExperiment No. lite3

# Function to update the selected product namesdef update_selected_products():


selected_products.set([product_name.get() for product_name in product_names])

# Create a function to fetch product names from the databasedef fetch_product_names():


# Connect to the database (replace 'your_database.db' with your database file)conn =
sExperiment No. lite3.connect('your_database.db')

cursor = conn.cursor()

# Fetch product names from the 'Product' table cursor.execute("SELECT Pname FROM Product")
product_name_list = [row[0] for row in cursor.fetchall()]

# Close the database connectionconn.close()

return product_name_list

6
# Create the main window root = tk.Tk() root.title("Product Selection")

# Fetch product names from the databaseproduct_names = fetch_product_names()

# Create a list of Checkbuttons for each productselected_products = tk.StringVar()


checkboxes = []

for product_name in product_names:


checkbox = tk.Checkbutton(root, text=product_name, variable=selected_products,
onvalue=product_name, offvalue="")
checkbox.pack() checkboxes.append(checkbox)

# Create a button to update selected products


update_button = tk.Button(root, text="Update Selected Products",command=update_selected_products)
update_button.pack()

# Start the main event looproot.mainloop()

We connect to the SEXPERIMENT NO. Lite database (replace 'your_database.db' with your actualdatabase
file path) and fetch the product names from the "Product" table.
We create a list of Checkbuttons, one for each product name. The selected_products variable is used to
keep track of the selected product names.
When the "Update Selected Products" button is clicked, it calls the update_selected_products function to
update the selected product names based onthe state of the Checkbuttons.

R 11
EXPERIMENT NO. 5.

Create a user control that display current date/time . Include it in a webform and refresh it each time
a button is clicked.
Ans:- Create the User Control (HTML, CSS, and JavaScript):

Create a user control (a standalone HTML file) that displays the current date andtime. You can use
JavaScript to update the time and refresh it when needed.

datetime_control.html:

<!DOCTYPE html>
<html>
<head>
<style>
/* CSS styles for the datetime display */#datetime {
font-size: 24px;
}
</style>
</head>
<body>
<div id="datetime">Loading...</div>

<script>
// JavaScript to update the datetimefunction updateDateTime() {
const datetimeElement = document.getElementById('datetime');

R 12
const currentDateTime = new Date().toLocaleString();datetimeElement.innerText =
currentDateTime;
}

// Initial call to update the datetimeupdateDateTime();

// Function to refresh datetime when the button is clickedfunction refreshDateTime() {


updateDateTime();
}
</script>
</body>
</html>

Create a Web Form:

Create an HTML web form (index.html) that includes the user control and a buttonto refresh the datetime.

index.html:
Explanation:

datetime_control.html contains the user control code that displays the current dateand time. JavaScript is
used to update the time and provide a function to refresh it.

In index.html, an <iframe> is used to include the user control (datetime_control.html) on the web form.
Additionally, a "Refresh" button is

provided, and clicking it updates the datetime by reloading the iframe with atimestamp parameter to
prevent caching.

Testing:
Open index.html in a web browser. You will see the current date and timedisplayed in the user control.
Clicking the "Refresh" button will update thedatetime without refreshing the entire page.

R 13
EXPERIMENT NO. 6.
Create a user control that contains a list of colors Add a button to theweb form and refresh it each
time a button is clicked.
Ans :- <?php
// Define an array of colors
$colors = array("Red", "Green", "Blue", "Yellow", "Purple", "Orange");

// Loop through the colors and create a listecho "<ul>";


foreach ($colors as $color) {echo "<li>$color</li>";
}
echo "</ul>";
?>
Create your main web form file, let's call it index.php. In this file, include the usercontrol and add a button
to refresh it:
<!DOCTYPE html>
<html>
<head>
<title>Color List</title>
</head>
<body>
<h1>Color List</h1>
<!-- Include the user control -->
<div id="color-list">
<?php include 'color_list.php'; ?>
</div>

<!-- Add a button to refresh the color list -->


<button onclick="refreshColorList()">Refresh</button>

<script>
function refreshColorList() {
// Use AJAX to refresh the color list without reloading the pagevar xhr = new XMLHttpReExperiment No.
uest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 &&xhr.status === 200) {
// Replace the content of the color list div with the updated list
document.getElementById("color-list").innerHTML = xhr.responseText;
}

};
xhr.open("GET", "color_list.php", true);xhr.send();
}
R 14
</script>
</body>

</html>
In this code, we include the color_list.php file in the div with the id "color-list" initially. Then, we add a
JavaScript function refreshColorList() that uses AJAX tofetch the updated color list from the
color_list.php file when the "Refresh" buttonis clicked. The response from the AJAX reExperiment No.
uest replaces the content of the "color-list" div, effectively updating the color list on the web page
without a full page refresh.

R 15
EXPERIMENT NO. 7.
Create a user control that contain a list of color. Add a button to the webform which when clicked
changes the color of the form to the color selected form the list.
Ans:- Create a new ASP.NET Web Application project or use an existing one.

Create a user control that includes the list of colors and the button. To do this,follow these steps:

a. Right-click on your project in Solution Explorer and select "Add" > "WebForm." Name it something
like "ColorSelector.ascx."

b. In the ColorSelector.ascx file, add the following markup:


<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ColorSelector.ascx.cs"
Inherits="YourNamespace.ColorSelector"
%>
<div>
<label>Select a Color:</label>
<asp:DropDownList ID="ddlColors" runat="server">
<asp:ListItem Text="Red" Value="Red" />
<asp:ListItem Text="Blue" Value="Blue" />
<asp:ListItem Text="Green" Value="Green" />
<asp:ListItem Text="Yellow" Value="Yellow" />
<!-- Add more colors as needed -->
</asp:DropDownList>
<asp:Button ID="btnChangeColor" runat="server" Text="Change Color"
OnClick="btnChangeColor_Click" />
</div>

In the code-behind file (ColorSelector.ascx.cs), add the following code to handlethe button click event and
change the background color of the parent page:

using System;
using System.Web.UI;

namespace YourNamespace
{
public partial class ColorSelector : UserControl
{
protected void Page_Load(object sender, EventArgs e)

R 16
{
}

protected void btnChangeColor_Click(object sender, EventArgs e)


{
string selectedColor = ddlColors.SelectedValue;Page page = this.Page;

// Change the background color of the parent pagepage.Style["background-color"] =


selectedColor;
}
}
}
Now, you can use this user control in your web form. Add a new web form (e.g.,Default.aspx) and include
the ColorSelector user control on it. You can do this byadding the following markup in the Default.aspx
file:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"


Inherits="YourNamespace.Default" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Color Change Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<!-- Include the ColorSelector user control -->
<uc:ColorSelector ID="ColorSelector1" runat="server" />
</div>
</form>
</body>
</html>

In the code-behind file (Default.aspx.cs) of your web form, you don't need to do anything related to color
changes since the logic is already implemented in the usercontrol.

Build and run your ASP.NET application. You'll see the color selection dropdownand the "Change Color"
button on the web form. When you select a color and clickthe button, the background color of the web form
will change accordingly.

R 17
EXPERIMENT NO. 8.
Write a simple PHP page that will display some information ontowebpage?

Ans:- <!DOCTYPE html>


<html>
<head>
<title>PHP Info Page</title>
</head>
<body>
<h1>Welcome to My PHP Info Page</h1>
<?php
// Define some information to display
$name = "John Doe";
$age = 30;
$city = "New York";

// Display the information on the webpageecho "<p>Name: $name</p>";


echo "<p>Age: $age</p>";echo "<p>City: $city</p>";
?>
</body>
</html>

Save this code in a .php file (e.g., info.php) and place it in your web server's rootdirectory. When you
access this PHP file in your web browser (e.g., http://localhost/info.php if you're running a local web
server), it will display the information provided in the PHP script on the webpage.

R 18
EXPERIMENT NO. 9.

Write a php script for the following design a form to accept a string. Write a function to count the
total number of Vowels (a,e,i,o,u) from the stringshow the occurrences of each vowel from the
string.

Ans:- <!DOCTYPE html>


<html>
<head>
<title>Vowel Counter</title>
</head>
<body>
<h1>Vowel Counter</h1>

<?php
// Define a function to count vowels and display occurrencesfunction countVowels($inputString) {
$inputString = strtolower($inputString); // Convert the input string tolowercase
$vowels = ['a' => 0, 'e' => 0, 'i' => 0, 'o' => 0, 'u' => 0]; // Initialize vowelcounts

for ($i = 0; $i<strlen($inputString); $i++) {


$char = $inputString[$i];
if (array_key_exists($char, $vowels)) {
$vowels[$char]++;
}
}

// Calculate the total number of vowels


$totalVowels = array_sum($vowels);

// Display the input string and vowel countsecho "<p>Input String: $inputString</p>"; echo "<p>Total
Vowels: $totalVowels</p>";echo "<p>Vowel Occurrences:</p>";
echo "<ul>";
foreach ($vowels as $vowel => $count) {echo "<li>$vowel: $count</li>";
}
echo "</ul>";
}

R 19
if ($_SERVER["REEXPERIMENT NO. UEST_METHOD"] == "POST") {
// Get the input string from the form
$inputString = $_POST["inputString"];countVowels($inputString);
}
?>

<form method="POST">
<label for="inputString">Enter a String:</label>
<input type="text" id="inputString" name="inputString" reExperiment No. uired>
<button type="submit">Count Vowels</button>
</form>
</body>
</html>

R 20
EXPERIMENT NO. 10.
Write a php script for the following design a form to accept two number from the user. Give options
to choose the arithmetic operation (useradio buttons.) display the result on the next form?

Ans:- index.php (the first form):

<!DOCTYPE html>
<html>
<head>
<title>Arithmetic Calculator</title>
</head>
<body>
<h1>Arithmetic Calculator</h1>
<form method="POST" action="calculate.php">
<label for="num1">Enter the first number:</label>
<input type="number" id="num1" name="num1" reExperiment No. uired><br><br>

<label for="num2">Enter the second number:</label>


<input type="number" id="num2" name="num2" reExperiment No. uired><br><br>

<label>Choose an operation:</label><br>
<input type="radio" id="addition" name="operation" value="addition" reExperiment No. uired>
<label for="addition">Addition</label><br>

<input type="radio" id="subtraction" name="operation" value="subtraction">


<label for="subtraction">Subtraction</label><br>

<input type="radio" id="multiplication" name="operation"value="multiplication">


<label for="multiplication">Multiplication</label><br>

<input type="radio" id="division" name="operation" value="division">


<label for="division">Division</label><br><br>

<button type="submit">Calculate</button>
</form>
</body>
</html>

calculate.php (the second form):

R 21
<!DOCTYPE html>
<html>
<head>
<title>Arithmetic Result</title>
</head>
<body>
<h1>Arithmetic Result</h1>
<?php
// Check if the form was submitted
if ($_SERVER["REEXPERIMENT NO. UEST_METHOD"] == "POST") {
// Get the input values and selected operation
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];
$operation = $_POST["operation"];

// Perform the selected operationswitch ($operation) {


case "addition":
$result = $num1 + $num2;break;
case "subtraction":
$result = $num1 - $num2;break;
case "multiplication":
$result = $num1 * $num2;break;
case "division":
if ($num2 != 0) {
$result = $num1 / $num2;
} else {
echo "Error: Division by zero is not allowed.";exit();
}
break;default:
echo "Invalid operation selected.";exit();
}

// Display the result


echo "<p>Result of $num1 $operation $num2 = $result</p>";

}
?>
<a href="index.php">Go Back</a>
</body>
</html>

R 22

You might also like