Escolar Documentos
Profissional Documentos
Cultura Documentos
(Autonomous)
ERODE – 638012.
Reg No : Semester : IV
Certified that this is a bonafide record of work done by the above student during
the year 2018 - 2019
Python Programs
PHP Programs
10
11
12
13
14
15
16
ARMSTRONG NUMBER
Ex.No:1
Date :
AIM:
ALGORITHM:
STEP6 : Find remainder of the input number by using the mod (%) operator to get each digit in the
number.
num=int(input("Enter a number:"))
sum=0
temp=num
while temp>0:
digit=temp%10
sum+=digit**3
temp//=10
if num==sum:
else:
OUTPUT:
Enter a number:121
Enter a number:153
RESULT:
Thus the above program has been executed successfully and verified.
SIMPLE CALCULATOR
Ex.No:2
Date :
AIM:
ALGORITHM:
CODING :
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
if select == 1:
print("result = ",res)
elif select == 2:
print("result = ",res)
elif select == 3:
print("result = ",res)
else:
print("result = ",res)
elif choice == 5:
print("Invalid input")
OUTPUT:
Enter Operation(1/2/3/4):1
Result=7
RESULT:
Thus the above program has been executed successfully and verified.
FACTORIAL OF A GIVEN NUMBER
Ex.No:3
Date :
AIM :
To Write a python program for Factorial Of the given number.
ALGORITHM:
STEP1 : Start the Process
STEP2 : Take a number from the user
STEP3 : Initialize a factorial variable to 1.
STEP4 : Use a while loop to multiply the number to the factorial variable and then decrement the
number.
STEP5 : Continue this till the value of the number is greater than 0.
STEP6 : Print the factorial of the number.
STEP7 : Stop the process
CODING:
num=int(raw_input("Enter a number"))
n=1
while num>0:
n=n*num
num=num-1
ENTER A NUMBER : 5
RESULT:
Thus the above program has been executed successfully and verified.
FIBONACCI SERIES
Ex.No:4
Date:
AIM :
ALGORITHM :
CODING:
n1=0
n2=1
i=2
if range1==0:
print n1
else:
print n1
print n2
while i<range1:
n3=n1+n2
print n3
n1=n2
n2=n3
i=i+1
OUTPUT:
RESULT:
Thus the above program has been executed successfully and verified.
MATRIX ADDITION
Ex.No:5
Date :
AIM:
Program to compute the sum of two matrices and then print it in Python.
ALGORITHM:
CODING:
M1=[[1,1,1],
[1,1,1],
[1,1,1]]
M2=[[1,2,3],
[4,5,6],
[7,8,9]]
sum=[[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
for i in range(len(M1)):
for j in range(len(M1[0])):
sum[i][j]=M1[i][j]+M2[i][j]
print(num)
OUTPUT:
[2,3,4,0]
[5,6,7,0]
[8,9,10,0]
RESULT:
Thus the above program has been executed successfully and verified.
MATRIX MULTIPLICATION
Ex.No:6
Date :
AIM:
Program to compute the Multiply of two matrices and then print it in Python
ALGORITHM:
CODING:
M1= [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
M2= [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
sum=[[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
for i in range(len(M1)):
for j in range(len(M1[0])):
for k in range(len(M2)):
print(num)
OUTPUT:
[12,15,27,0]
[24,30,54,0]
[36,45,81,0]
RESULT:
Thus the above program has been executed successfully and verified.
PALINDROME OR NOT
Ex.No:7
Date :
AIM :
To write a python program to check whether the given string is palindrome or not.
ALGORITHM :
CODING:
string=raw_input("Enter String:")
if(string==string[::-1]):
else:
RESULT :
Thus the above program has been executed successfully and verified.
PRIME NUMBER OR NOT
Ex.No:8
Date :
AIM :
To write a python program to check whether the given number is prime number or not.
ALGORITHM :
CODING :
num = 407
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(i,"times",num//i,"is",num)
break
else:
OUTPUT :
RESULT :
Thus the above program has been executed successfully and verified.
REVERSE A STRING USING STACK
Ex.No:9
Date :
AIM :
ALGORITHM:
STEP2 : Create a class Stack with instance variable items initialized to an empty list.
STEP3 : Define methods push, pop, is_empty and display inside the class Stack.
STEP7 : The method display prints the elements of the stack from top to bottom.
STEP8 : Create an instance of Stack, push data to it and reverse the stack.
CODING:
def createStack():
stack=[]
return stack
def size(stack):
return len(stack)
def isEmpty(stack):
if size(stack) == 0:
return true
def push(stack,item):
stack.append(item)
def pop(stack):
if isEmpty(stack): return
return stack.pop()
def reverse(string):
n = len(string)
stack=createStack()
for i in range(0,n,1):
push(stack,string[i])
string=" "
for i in range(0,n,1):
string+=pop(stack)
return string
s="velalar"
print(s)
print(reverse(s))
OUTPUT :
velalar
ralalev
RESULT :
Thus the above program has been executed successfully and verified.
BINARY SEARCH PROGRAM USING PHP
Ex.No. : 10
Date :
AIM :
To write a PHP Script to find the presence of an item using Binary Search.
ALGORITHM :
CODING :
<?php
OUTPUT :
5. Exists
RESULT :
Thus the above program binary search has been executed successfully and verified.
SIMPLE CALCULATOR PROGRAM USING PHP
Ex.No. : 11
Date :
AIM :
ALGORITHM :
CODING :
<?php
if(isset($_POST['sub']))
{
$txt1=$_POST['n1'];
$txt2=$_POST['n2'];
$oprnd=$_POST['sub'];
if($oprnd=="+")
$res=$txt1+$txt2;
else if($oprnd=="-")
$res=$txt1-$txt2;
else if($oprnd=="x")
$res=$txt1*$txt2;
else if($oprnd=="/")
$res=$txt1/$txt2;
}
?>
RESULT :
Thus the above program calculator has been successfully executed and verified.
UPLOADING A FILE USING PHP
Ex.No. : 12
Date :
AIM :
ALGORITHM :
CODING:
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$extensions= array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false)
{
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152)
{
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true)
{
move_uploaded_file($file_tmp,"sharmi/".$file_name);
echo "Success";
}else
{
print_r($errors);
}
}
?>
<html>
<body>
<form action = "" method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "image" />
<input type = "submit"/>
<ul>
<li>Sent file: <?php echo $_FILES['image']['name']; ?>
<li>File size: <?php echo $_FILES['image']['size']; ?>
<li>File type: <?php echo $_FILES['image']['type'] ?>
</ul> </form>
</body>
</html>
OUTPUT :
RESULT:
Thus the above program uploading a file has been successfully executed and verified.
FORM VALIDATION USING PHP
Ex.No. : 13
Date :
AIM :
ALGORITHM :
CODING:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
function validate($str) {
return trim(htmlspecialchars($str));
}
if (empty($_POST['name'])) {
$nameError = 'Name should be filled';
} else {
$name = validate($_POST['name']);
if (!preg_match('/^[a-zA-Z0-9\s]+$/', $name)) {
$nameError = 'Name can only contain letters, numbers and white spaces';
}}
if (empty($_POST['email'])) {
$emailError = 'Please enter your email';
} else {
$email = validate($_POST['email']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = 'Invalid Email';
}}
if (empty($_POST['password'])) {
$passwordError = 'Password cannot be empty';
} else {
$password = validate($_POST['password']);
if (strlen($password) < 6) {
$passwordError = 'Please should be longer than 6 characters';
}}
if (empty($_POST['gender'])) {
$genderError = 'Please enter your gender';
} else {
$gender = $_POST['gender'];
}
$remember = !empty($_POST['remember']) ? filter_var($_POST['remember'],
FILTER_VALIDATE_BOOLEAN) : "";
if (empty($nameError) && empty($emailError) && empty($passwordError) &&
empty($genderError)) {
echo "You have filled the form successfully!";
echo "<br>
Name: $name <br>
Email: $email <br>
Password: $password <br>
Gender: $gender <br>
Remember Me: $remember";
exit();
}}
?>
<html>
<head>
<title>Complete Form</title>
<style type="text/css">
.error {
color:red; }
</style>
</head>
<body>
<form method="POST" action="">
Name:
<input type="text" name="name" value="<?php if (isset($name)) echo $name ?>">
<span class="error"><?php if (isset($nameError)) echo $nameError ?></span><br>
Email:
<input type="text" name="email" value="<?php if (isset($email)) echo $email ?>">
<span class="error"><?php if (isset($emailError)) echo $emailError ?></span><br>
Password:
<input type="password" name="password">
<span class="error"><?php if (isset($passwordError)) echo $passwordError ?></span><br>
Gender:
Male
<input type="radio" name="gender" value="male" <?php if (isset($gender) && $gender
=== "male") echo "checked" ?>>
Female
<input type="radio" name="gender" value="female" <?php if (isset($gender) &&
$gender === "female") echo "checked" ?>>
<span class="error"><?php if (isset($genderError)) echo $genderError ?></span> <br>
Remember Me:
<input type="checkbox" name="remember">
<input type="submit" name="submit">
</form>
</body>
</html>
OUTPUT :
You have filled the form successfully!
Name: pooja
Email: pooja@gmail.com
Password: 456456h
Gender: female
Remember Me:
RESULT :
Thus the above program validation has been successfully executed and verified.
WEB FORM CREATION USING PHP
Ex.No. : 14
Date :
AIM:
To write a PHP program to create a simple web form using different form elements.
ALGORITHM:
CODING :
<html>
<head><title></title>
</head>
<body>
<form method="post" action="index.php">
<table>
<tr><td>NAME:</td>
<td><input type="text" name="name" required=""></td></tr>
<tr><td>ROLL NO:</td>
<td><input type="text" name="roll" required=""></td></tr>
<tr><td>HOBBY:</td>
<td><input type="checkbox" name="hobbie[]" value="READING">READING
<input type="checkbox" name="hobbie[]" value="PLAYING GAMES">PLAYING GAMES
<?php
$name=$_POST['name'];
$roll=$_POST['roll'];
$gender=$_POST['gender'];
$hobbie=$_POST['hobbie'];
$branch=$_POST['branches'];
if(isset($_POST['submit']))
{
echo"NAME:$name<br>";
echo"ROLL NO:$roll<br>";
echo"GENDER:$gender<br>";
echo"HOBBIE:";
foreach($_POST['hobbie'] as $selected){
echo "$selected ";}
echo"<br>BRANCH:$branch<br>";
}
?>
</body>
</html>
OUTPUT :
NAME: abi
ROLL NO: 02
BRANCH: MCA
save cancel
NAME:abi
ROLL NO:02
GENDER:FEMALE
HOBBIE:INTERNET SURFFING
BRANCH:MCA
RESULT :
Thus the above program web forms has been executed successfully and verified.
DATABASE OPERATIONS USING PHP
Ex.No. : 15
Date :
AIM :
To write the PHP program for database connectivity and to perform various database
operations like insert, delete, update and search.
ALGORITHM :
STEP 1 : Start the php program.
STEP 2 : Create the connection to database using my sql_connect then create the table with rows
and columns for necessary fields to be placed.
STEP 3 : Then use select, insert update, delete commands for inserting, deleting and updating
records.
STEP 4 : Then using form display all the details in the table.
STEP 5 : Save the program and run it.
STEP 6 : Stop the process.
CODING:
<?php
$host = "localhost";
$user = "root";
$password ="";
$database = "test_db";
$id = "";
$fname = "";
$lname = "";
$age = "";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = mysqli_connect($host, $user, $password, $database);
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['fname'];
$posts[2] = $_POST['lname'];
$posts[3] = $_POST['age'];
return $posts;
}
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM users WHERE id = $data[0]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$fname = $row['fname'];
$lname = $row['lname'];
$age = $row['age'];
}
}else{
echo 'No Data For This Id';
}
}else{
echo 'Result Error';
}
}
if(isset($_POST['insert']))
{
$data = getPosts();
$insert_Query = "INSERT INTO `users`(`fname`, `lname`, `age`)VALUES('$data[1]','$data[2]',$data[3])";
$insert_Result = mysqli_query($connect, $insert_Query);
if($insert_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Inserted';
}else
{
echo 'Data Not Inserted';
}
}
}
if(isset($_POST['delete']))
{
$data = getPosts();
$delete_Query = "DELETE FROM `users` WHERE `id` = $data[0]";
$delete_Result = mysqli_query($connect, $delete_Query);
if($delete_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Deleted';
}else{
echo 'Data Not Deleted';
}}}
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `users` SET `fname`='$data[1]',`lname`='$data[2]',`age`=$data[3]
WHERE `id` = $data[0]";
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}}}
?>
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<input type="number" name="id" placeholder="Id" value="<?php echo $id;?>"><br><br>
<input type="text" name="fname" placeholder="First Name" value="<?php echo
$fname;?>"><br><br>
<input type="text" name="lname" placeholder="Last Name" value="<?php echo
$lname;?>"><br><br>
<input type="number" name="age" placeholder="Age" value="<?php echo $age;?>">
<br><br>
<div>
<input type="submit" name="insert" value="Add">
<input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete">
<input type="submit" name="search" value="Find">
</div>
</form>
</body>
</html>
OUTPUT :
RESULT :
Thus the above program DataBase Connectivity has been executed successfully and
verified.
USER LOGIN AND REGISTRATION FORM IN PHP
Ex.No. : 16
Date :
AIM:
ALGORITHM :
STEP2 : Create the connection to database using my sql_connect then create the table with rows
and columns for necessary fields to be placed.
STEP3 : select the database and checking, if the form is submitted or not.
STEP4 : If the form is submitted, then assigning the posted values to variables and checking the
values are existing in the database or not.
STEP5 : If the values submitted in the form and the values in the database are equal, then we will
create a session for the user.
STEP6 : If the values are not equal then it will display an error message.
STEP7 : And then we checks for the session, if the session exists we will great him with the
username, otherwise the form will be displayed.
STEP8 : When the user comes first time, that will be displayed with a simple form.
STEP9 : Given the User Name, Password and a submit button.
STEP10 : Submit the values to the buttons, If the values submitted in the form and the values in the
database are equal, then we will create a registration for the user.
STEP11 : Stop the program.
CODING:
LOGIN FORM:
<html>
<head>
<title>User Login Form - PHP MySQL Login System </title>
</head>
<body><center>
<h1>User Login Form - PHP MySQL Login System </h1></center>
<?php
if (!isset($_POST['submit'])){
?>
<center>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post"><table>
<tr><td>Username:</td><td> <input type="text" name="username" ></td></tr>
<tr><td>Password:</td><td> <input type="password" name="password"></td></tr>
<tr><td><input type="submit" name="submit" value="Login" ></td><td><li>
<a href="register.php">New
User</a></li></td></tr></table>
</form>
</center>
<?php
} else {
require_once("login.php");
$mysqli = new mysqli($host, $user, $pass, $database);
REGISTRATION FORM :
<?php
$conn_error = 'Could not connect.';
$host = "localhost";
$user = "root";
$pass ="";
$database = "logreg";
?>
<html>
<head>
<title>User registration form- PHP MySQL Login System </title>
</head>
<body> <center>
<h1>User registration form- PHP MySQL Login System </h1></center>
<?php
if (!isset($_POST['submit'])) {
?><center>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post"><table>
<tr><td>First name:</td> <td><input type="text" name="first_name" ></td>
<td>Last name:</td><td> <input type="text" name="last_name" ></td></tr>
<tr><td>Username:</td><td> <input type="text" name="username" ></td></tr>
<tr><td>Email:</td><td> <input type="type" name="email" ></td></tr>
<tr><td>Password:</td><td> <input type="password" name="password" ></td></tr>
<tr><td><input type="submit" name="submit" value="Register" ></td><td><li>
<a href="login1.php">Already
User</a></li></td></tr></table>
</form></center>
<?php
} else {
require_once("register.php");
$mysqli = new mysqli($host, $user, $pass, $database);
if(!mysqli_connect($host, $user, $pass, $database))
{
die($conn_error);
}
else
{
echo 'connected';
}
$username = $_POST['username'];
$password = $_POST['password'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$exists = 0;
$result = $mysqli->query("SELECT username from users WHERE username = '{$username}'
LIMIT 1");
if ($result->num_rows == 1)
{
$exists = 1;
echo "<p>Username already exists!</p>";
}
else
{
$sql = "INSERT INTO `users` (`id`, `username`, `password`, `first_name`, `last_name`, `email`)
VALUES (NULL, '{$username}', '{$password}', '{$first_name}', '{$last_name}',
'{$email}')";
if ($mysqli->query($sql)){
echo "<p>Registred successfully!</p>";
} else
{
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
}
}
?>
</body> </html>
OUTPUT :
RESULT :
Thus the above program User Login and Registration form has been executed successfully
and verified.