Você está na página 1de 47

VELALAR COLLEGE OF ENGINEERING AND TECHNOLOGY

(Autonomous)
ERODE – 638012.

Name : Branch : M.C.A.

Reg No : Semester : IV

Subject: Open Source Technologies Laboratory Subject code: 16CAL42

Certified that this is a bonafide record of work done by the above student during
the year 2018 - 2019

Staff-in-charge Head of the department

Submitted for the Practical Examination held on...................................................

Internal Examiner External Examiner


INDEX

S.No Date Contents Page. No. Mark Signature

Python Programs

PHP Programs

10

11

12

13

14

15

16
ARMSTRONG NUMBER

Ex.No:1

Date :

AIM:

To Write a python program for Armstrong Number

ALGORITHM:

STEP1: Start the process.

STEP2 : Read an input number using input() or raw_input().

STEP3 : Check whether the value entered is an integer or not.

STEP4 : Check temp is greater than 0 using while loop.

STEP5 : Initialize a variable named SUM to 0.

STEP6 : Find remainder of the input number by using the mod (%) operator to get each digit in the
number.

STEP7 : Stop the process.


CODING:

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

sum=0

temp=num

while temp>0:

digit=temp%10

sum+=digit**3

temp//=10

if num==sum:

print("This number is Amstrong number")

else:

print("This number is not a Amstrong number")

OUTPUT:

Enter a number:121

This number is not an Amstrong number.

Enter a number:153

This number is an Amstrong number.

RESULT:

Thus the above program has been executed successfully and verified.
SIMPLE CALCULATOR

Ex.No:2

Date :

AIM:

To Write a python program for simple calculator using forms.

ALGORITHM:

STEP1 : Start the Process


STEP2 : User choose the desired operation. Options 1, 2, 3 and 4 are valid.
STEP3 : Two numbers are taken and an if…elif…else branching is used to execute a particular
section.
STEP4 : Using functions add(), subtract(), multiply() and divide() evaluate respective operations.
STEP5 : Stop the Process

CODING :

def add(num1, num2):

return num1 + num2

def subtract(num1, num2):

return num1 - num2

def multiply(num1, num2):

return num1 * num2

def divide(num1, num2):

return num1 / num2

print("Select operation.")

print("1.Add")

print("2.Subtract")
print("3.Multiply")

print("4.Divide")

select = input("Enter operation(1/2/3/4):");

if (select>=1 and select<=4):

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))

if select == 1:

res = num1 + num2;

print("result = ",res)

elif select == 2:

res = num1 - num2;

print("result = ",res)

elif select == 3:

res = num1 * num2;

print("result = ",res)

else:

res = num1 / num2;

print("result = ",res)

elif choice == 5:

print("Invalid input")
OUTPUT:

Enter Operation(1/2/3/4):1

Enter First Number:5

Enter Second Number:2

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

print"The factorial of the given number is",n


OUTPUT:

ENTER A NUMBER : 5

THE FACTORIAL OF THE GIVEN NUMBER IS 120

RESULT:

Thus the above program has been executed successfully and verified.
FIBONACCI SERIES

Ex.No:4

Date:

AIM :

To Write a python program for Fibonacci Of the given number.

ALGORITHM :

STEP1 : Start the Process


STEP2 : Read an input number using input() or raw_input().
STEP3 : Check whether the value entered is an integer or not.
STEP4 : Initialize a variable named n1= 0,n2=1.
STEP5:While loop will make sure that, the loop will start from 0 and it is less than the user given
number. Within the While loop of fibonacci series in python program, we used If statement.
 If i value is less than or equal to 1 then, Next will be i
 If i value is greater than 1, perform calculations inside the Else block
STEP6 : Calculate Fibonacci using formula n3=n1+n2
STEP7 : Stop the process.

CODING:

range1=int(raw_input("Enter the number of elements of the series"))

n1=0

n2=1

i=2

if range1==0:

print "Enter a positive integer"


elif range1==1:

print "fibonacci series upto",range1,":"

print n1

else:

print "Fibonacci series upto",range1,":"

print n1

print n2

while i<range1:

n3=n1+n2

print n3

n1=n2

n2=n3

i=i+1
OUTPUT:

ENTER THE NUMBER OFD ELEMENTS OF THE SERIES:6

FIBONACCI SERIES UPTO 6:

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:

STEP1 : Start the Process


STEP2 : Declare 2 matrix with rows and columns
STEP3 : Declare 3rd matrix to store the result
STEP4 : Use for loop to define the length of the matrix
STEP5 : Add the two matrix and store the result in 3rd matrix
STEP6 : Finally print the result.

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]

for num in sum:

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:

STEP1 : Start the Process


STEP2 : Declare 2 matrix with rows and columns
STEP3 : Declare 3rd matrix to store the result
STEP4 : Use for loop to define the length of the matrix
STEP5 : Multiply the two matrix and store the result in 3rd matrix
STEP6 : Finally print the result.

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)):

sum[i][j]= M1[i][k] * M2[k][j]

for num in sum:

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 :

STEP1 : Start the process.


STEP2 : Take the string and store in a variable.
STEP3 : Transfer the string into another temporary variable.
STEP4 : Using a while loop, get each digit of the number and store the reversed string in another
variable.
STEP5 : Check if the reverse of the string is equal to the one in the temporary variable.
STEP6 : Print the final result.
STEP7 : Stop the process.

CODING:

string=raw_input("Enter String:")

if(string==string[::-1]):

print("The string is a palindrome")

else:

print("The string is not a palindrome")


OUTPUT :

Enter String : madam

This string is a Palindrome.

Enter String : good

This string is not a palindrome.

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 :

STEP 1: start the program.


STEP 2: Input number as num=407.
STEP 3: For any number i between 2 and n - 1, check if num % i == 0
STEP 4: Continue the loop till the end or till n is divisible by any value of i.
STEP 5: If n % i == 0 for any value of i, then break/exit the loop. The number is not
prime.
STEP 6: Otherwise if n % i != 0 for any value of i, then continue the loop till the end,
and declare the number as prime.
STEP 7: stop the program.

CODING :

num = 407

if num > 1:

for i in range(2,num):

if (num % i) == 0:

print(num,"is not a prime number")

print(i,"times",num//i,"is",num)

break

else:

print(num,"is a prime number")


else:

print(num,"is not a prime number")

OUTPUT :

(407,’ is not a prime number’)

(11, ‘times’, 37, ‘is’, 407)

RESULT :

Thus the above program has been executed successfully and verified.
REVERSE A STRING USING STACK

Ex.No:9

Date :

AIM :

To write a python program for Reverse String Using Stack.

ALGORITHM:

STEP1 : Start the process

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.

STEP4 : The method push appends data to items.

STEP5 : The method pop pops the first element in items.

STEP6 : The method is_empty returns True only if items is empty.

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("The Original String is : ")

print(s)

print("The Reversed String using Stack is : ")

print(reverse(s))
OUTPUT :

The Original string is :

velalar

The Reversed String using Stack is :

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 :

STEP1 : Start the Process.


STEP2 : Sort the array as binary search only works on sorted ranges
STEP3 : Compute the middle element if the element we wish to search is greater than the middle
element search on the right side else search on the left.
STEP4 : Return True if the element is found.
STEP5 : Stop the Process.

CODING :

<?php

function binarySearch(Array $arr, $x)


{
if (count($arr) === 0) return false;
$low = 0;
$high = count($arr) - 1;
while ($low <= $high)
{
$mid = floor(($low + $high) / 2);
if($arr[$mid] == $x)
{
return true;
}
if ($x < $arr[$mid])
{
$high = $mid -1;
}
else
{
$low = $mid + 1;
}
}
return false;
}

$arr = array(1, 2, 3, 4);


$value = 5;
if(binarySearch($arr, $value) == true)
{
echo $value." Exists";
}
else
{
echo $value." Doesnt Exist";
}
?>

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 :

To write a PHP program to create a simple calculator.

ALGORITHM :

STEP 1 : Start the program


STEP 2 : Create a form using post method
STEP 3 : Create text boxes named n1,n2,res and buttons named sub to perform operations like
addition, subtraction, multiplication and division.
STEP 4 : Open PHP and use isset() function
STEP 5 : If operator + is received using post method , perform addition operation or else perform
subtraction or multiplication or division operation
STEP 6 : Store the result in res variable
STEP 7 : Stop the program.

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;
}
?>

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


Calculator
<br>
No1:<input name="n1" value="<?php echo $txt1; ?>"><br>
No2:<input name="n2" value="<?php echo $txt2; ?>"><br>
Res:<input name="res" value="<?php echo $res; ?>"><br>
<input type="submit" name="sub" value="+">
<input type="submit" name="sub" value="-">
<input type="submit" name="sub" value="x">
<input type="submit" name="sub" value="/">
</form>
OUTPUT :

RESULT :

Thus the above program calculator has been successfully executed and verified.
UPLOADING A FILE USING PHP

Ex.No. : 12

Date :

AIM :

To write a PHP program for uploading a file.

ALGORITHM :

STEP1 : Start the process.


STEP2 : The user opens the page containing a HTML form featuring a text files, a browse button
and a submit button.
STEP3 : The user clicks the browse button and selects a file to upload from the local PC.
STEP4 : The full path to the selected file appears in the text filed then the user clicks the submit
button.
STEP5 : The selected file is sent to the temporary directory on the server.
STEP6 : The PHP script that was specified as the form handler in the form's action attribute checks
that the file has arrived and then copies the file into an intended directory.
STEP7 : Stop the process.

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 :

To write the php program for form validation.

ALGORITHM :

STEP1: Start the php program.


STEP2 : Create the form using post method.
STEP3 : Then create the necessary fields like name,email,password.
STEP4 : Use the validating conditions for validating the fields.
STEP5 : save the program and run it.
STEP6 : Stop the process.

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:

STEP1: Start the program


STEP2: Create a form using HTML tag
STEP3: Create some fields like name, roll in text type and hobby in check box, gender in radio
button and branch in drop down list
STEP4: Open PHP and get the fields using the post method and store it in variable
STEP5: Use the isset() function to print all the values using the echo statement
STEP6: Stop the program

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

<input type="checkbox"name="hobbie[]"value="INTERNET SURFFING">INTERNET


SURFFING </td></tr>
<tr><td>GENDER:</td>
<td><input type="radio" name="gender" value="male">MALE<input type="radio"
name="gender"
value="female">FEMALE</td></tr>
<tr><td>BRANCH:</td><td><select name="branches"><option>MCA</option>
<option>CSE</option>
<option>EEE</option>
<option>IT</option>
<option>ECE</option>
<option>BME</option>
<option>CIVIL</option>
<option>MCA2</option>
</select></td>
<tr><td><input type="submit" name="submit" value="save"></td>
<td><input type="reset" value="cancel"></td></tr>
</table></form>

<?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

HOBBY: READING PLAYING GAMES INTERNET SURFFING

GENDER: MALE FEMALE

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:

To write a program for Userlogin and Registration form using PHP.

ALGORITHM :

STEP1 : Start the program.

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);

if(!mysqli_connect($host, $user, $pass, $database))


{
die($conn_error);}
else
{
echo 'connected';
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from users WHERE username LIKE '{$username}' AND password
LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
} else {
echo "<p>Logged in successfully</p>";
}}
?>
</body>
</html>

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.

Você também pode gostar