PHP Assignments
PHP Assignments
Write a PHP program to calculate sum of digits of given number, also count number of zeros,
odd digits and even digit (using loop).
Code: -
<?php
function analyzeNumber($number) {
$numberStr = (string)$number;
$sum = 0;
$countZeros = 0;
$countOdd = 0;
$countEven = 0;
$digit = (int)$numberStr[$i];
$sum += $digit
if ($digit === 0) {
$countZeros++;
$countEven++;
} else {
$countOdd++;
}
echo "Sum of digits: $sum<br>";
$countEven<br>";
}
?>
Output: -
Q.Write a PHP program to count number of times a user has visited a web page using
session.
Code: - <?
php
session_start();
if (isset($_SESSION['visit_count'])) {
$_SESSION['visit_count']++;
} else {
$_SESSION['visit_count'] = 1;
}
$visit_count = $_SESSION['visit_count'];
echo "<p>You've visited this page $visit_counttimes.</p>";
?>
Output: -
Q.Write a PHP program to change background text color of web page using cookie.
Code: -
<?php
$Cookie_name="color";
$cookie_value="BLUE";
setcookie($cookie_name,$cookie_value,time()+(86400*30),"/");
?>
<html>
<body><?php
if(!isset($_COOKIE[$cookie_name]))
{
echo"Cookie not set";
}
else
{
echo"Cookie is set";
}
?>
</html>
</body>
Output:-
<html>
<head>
<title>Cookie Color Change</title>
</head>
<body>
<form><?php
echo "Cookie Value:".$_COOKIE["Color"];
$Color=$_COOKIE["Color"];
echo"<h1 Style=background-Color:$Color>Cookies change Color</h1>"
?>
</form>
</body>
Output: -
Q. Write a PHP program on connecting to database and perform crud
operation. Code: - header.php<html>
<head>
</head>
<title>Crud
</title>
<body>
<h1>crud</h1>
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="add.php">Add</a></li>
<li><a href="deletedata.php">delete</a></li>
</ul>
</body>
</html>
<?php
?>
Index.php<?php
include
'heder.php';
$conn=mysqli_connect("localhost","root","","crud")or die("connection failed"); $sql="select
* from student inner join course on student.sclass=course.cid"; $result=mysqli_query($conn,
$sql)or die("query unsuccessful"); if(mysqli_num_rows($result)>0)
{
echo"<table border>";
echo"<tr>";
echo"<th>id";
echo"<th>name";
echo"<th>address";
echo"<th>class";
echo"<th>phone";
echo"<th>action";
echo"</tr>";
while($row=mysqli_fetch_assoc($result))
{ echo"<tr>"; echo"<td>".
$row['sid']; echo"<td>".
$row['sname'];
echo"<td>".$row['saddr'];
echo"<td>".$row['sclass'];
echo"<td>".
$row['sphone'];
$rid=$row['sid'];
echo"<td><a
href='edit.php?id=$rid'>Edit</a><a
href='deletes.php?id=$rid'>Delete</a>"; echo
"</tr>";
}
}
?>
Output: -
Add.php
<html>
<head>
<title>Adding a Record
</title>
</head>
<body>
<form action = "save.php" method="post">
<table border>
<tr>
</br>
<td><label>Name</label></td>
<td><input type = "text" name="sname"/></td>
</br>
</tr>
<tr>
<td><label>Address</label></td>
<td><input type = "text" name="saddr"/></td>
</tr>
</br>
</br>
<tr>
<td><label>Class</label></td>
<td><select name="sclass" id="">
<option value="" selected disabled >Select Class</option>
<?php
$conn=mysqli_connect("localhost","root","","crud")or die("connection failed");
$sql="select * from course";
$result=mysqli_query($conn,$sql)or die("query unsuccessfully");
while($row=mysqli_fetch_assoc($result))
{
echo"<option value=".$row['cid'].">".$row['cname']."</option>";
}
?>
</select></td>
</tr>
<tr>
<td><lebel>phone</lebel></td>
<td><input type="text" name="sphone"/></td>
</tr>
</br>
</br>
<tr>
<tdalign="center"><input type="submit" name="submit" value="save"></td>
</tr>
</table></form>
</body>
</html>
Output: -
Save.php<?php
echo $s_name=$_POST['sname'];
echo $s_add=$_POST['saddr'];
echo $s_class=$_POST['sclass'];
echo
$s_phone=$_POST['sphone'];
$conn=mysqli_connect("localhost","root","","crud")or die("connection failed");
$sql="insert into
student(sname,saddr,sclass,sphone)values('{$s_name}','{$s_add}','{$s_class}','{$s_phone}');
$result=mysqli_query($conn,$sql)or die("query
unsuccessfully"); header("Location:
http://localhost/ss/index.php");mysqli_close($conn);
?>
Output: -
Edit.php
<?php
$conn = mysqli_connect("localhost","root","","crud") or die ("Connection unsucessfuly");
$stud_id=$_GET['id'];
$sql="select * from student where sid={$stud_id}";
$result = mysqli_query($conn,$sql) or die ("query unsuccessfully");
if(mysqli_num_rows($result)>0)
{
while($row=mysqli_fetch_assoc($result))
{
?>
<html>
<body>
<form action='update.php' method='post'>
<table border>
<tr>
</br>
<td><label>Name</label></td>
<input type="hidden" name="sid" value="<?php echo $row['sid']; ?>" >
<td><input type="text" name="sname" value="<?php echo $row['sname']; ?>"/></td>
</br>
</tr>
<tr>
<td><label>Address</label></td>
<td><input type="text" name="saddr" value="<?php echo $row['saddr']; ?>" /></td>
</tr>
</br>
</br>
<tr>
<td><label>Phone</label></td>
<td><input type="text" name="sphone" value="<?php echo $row['sphone']; ?>"></td>
</tr>
</br>
</br>
<tr>
<td><label>Class</label></td>
<!--<td><select name="sclass" id="">-->
<?php
$sql="select * from course";
$result1 = mysqli_query($conn,$sql) or die ("query
unsuccessfully"); //echo '<option value="" selected disabled>Select
Class</option>'; if(mysqli_num_rows($result1)>0)
{
echo '<td><select name="sclass">';
while($row1=mysqli_fetch_assoc($result1))
{
if($row['sclass']==$row1['cid']){
$select="selected";
}
else{
$select = " ";
}
echo "<option {$select} value='{$row1['cid']}'>{$row1['cname']}</option>";
}
echo "</select></td>";
}
?>
</tr>
<tr>
<tdalign="center"><input type="submit" name="update" value="update"></td>
</tr>
<?php
}
}
?>
</body></html>update.php<?php
echo "update page"; echo
$s_id=$_POST['sid']; echo
$s_name=$_POST['sname']; echo
$s_add=$_POST['saddr']; echo
$s_class=$_POST['sclass']; echo
$s_phone=$_POST['sphone'];
$conn= mysqli_connect("localhost","root","","crud")or die ("failed"); $sql="update student
set sname='{$s_name}',saddr='{$s_add}',sclass='{$s_class}',sphone='{$s_phone}' where
sid={$s_id}";
$result=mysqli_query($conn,$sql) or die("query unsucessful");
header("Location:http://localhost/ss/index.php");mysqli_close($conn);
?>
Output: -
deletedata.php<?
php include
"heder.php";
if(isset($_POST['de
lete']))
{
include "config.php";
$stud_id=$_POST['sid'];
$conn=mysqli_connect("localhost","root","","crud")or die("connection failed");
//$sql1="delete from student where sid={$stud_id}";
//$result=mysqli_query($conn,$sql)or die("query
unsuccessfully"); header("Location:
http://localhost/ss/index.php");mysqli_close($conn);
}
?>
<html>
<head>
<title>deleting record</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<table border>
<tr>
</br>
<td><label>sid</label></td>
<td><input type="text" name="sid"/></td>
</br>
</tr>
<tr>
<tdalign="center"><input type="submit" name="delete" value="delete"></td>
</tr>
</form>
</body>
</html>deletepg.php:
- <?php
//include "header.php";
//include "config.php"; echo
$stud_id=$_POST['sid'];
//$sql1="delete from studet where sid={$stud_id}";
//$result=mysqli_query($conn,$sql1)or die("query unsuccessfully");
//header("Location:http://localhost/ss/index.php");
?>
Output: -
Q. Write a PHP program to connect to mysql database employee master and perform
crud operation. the table master consistence following fields employee (eid)
(autogenerated and primary key),employee name and gender.
Code: -
E_header.php
<html>
<head>
</head>
<title>CRUD</title>
<body>
<h1>Employee Table(CRUD)</h1>
<ul>
<li><a href="E_index.php">home</a></li>
<li><a href="E_add.php">add</a></li>
<li><a href="E_deletedata.php">delete</a></li>
</ul>
</body>
</html>
<?php
?>
E_index.php
<?php include
"e_header.php";
$conn= mysqli_connect("localhost:3307","root","","employe_master")or die ("failed");
$sql = "SELECT * FROM employe";
$result=mysqli_query($conn,$sql) or die("query unsucessful");
if(mysqli_num_rows($result)>0)
{ echo"<table
border>";
echo"<tr>"; echo"<th>E_ID";
echo"<th>E_name";
echo"<th>E_gender";
echo"<th>action";
echo"<tr>";
while($rows=mysqli_fetch_assoc($result))
{ echo"<tr>"; echo"<td>".
$rows["eid"]; echo"<td>".
$rows["employee_name"];
echo"<td>".$rows["gender"];
$rid=$rows['eid'];
echo"<td><a href='edit_form.php?id=$rid'>edit</a>
<a href='E_delete.php?id=$rid'>delete</a></td>";
}
}
?>
Output : -
E_add.php
<?php
$h="Add Page";
echo '<h2>'.$h.'</h2>';
?>
<html>
<head>
<title>Adding Record</title>
</head>
<body>
<tr>
</tr>
<tr>
<tr>
<td><label for="gender">Gender:</label></td>
</td>
</tr>
</tr>
<tr>
</td>
</tr>
</table>
</form>
</body>
</html>
E_savedata.php
<?php
//echo $s_eid=$_POST['eid']; echo
$s_ename=$_POST['employee_name'];
echo $s_gender=$_POST['gender'];
$conn = mysqli_connect("localhost:3307","root","","employe_master") or die ("Connection
unsucessfuly");
$sql1="insert into employe(employee_name,gender)values('{$s_ename}','{$s_gender}')";
$result = mysqli_query($conn,$sql1) or die ("query unsuccessfully");
//header("C:\xampp\htdocs\meghaphp/index.php");
header("Location:http://localhost/meghaphp/ragister/E_index.php");mysqli_close($conn);
?>
Output: -
E_update.php<?
php echo "update
page";
$s_ename = $_POST['employee_name'];
$s_gender = $_POST['gender'];
$s_eid = $_POST['id'];
$conn = mysqli_connect("localhost:3307", "root", "", "employe_master") or die("Connection
failed");
$sql = "UPDATE employe SET employee_name='{$s_ename}', gender='{$s_gender}'
WHERE eid={$s_eid}";
$result = mysqli_query($conn, $sql);
header("Location:http://localhost/meghaphp/ragister/E_index.php");mysqli_close($conn);
?>
Edit_form.php
<?php
$h="Update Record"; echo
'<h2>'.$h.'</h2>';
$conn = mysqli_connect("localhost:3307","root","","employe_master") or die ("Connection
unsucessfuly");
$_eid=$_GET['id'];
$sql1="select * from employe where eid={$_eid}";
$result = mysqli_query($conn,$sql1) or die ("query unsuccessfully");
if(mysqli_num_rows($result)>0)
{
while($row=mysqli_fetch_assoc($result))
{
?>
<html>
<head>
<title>update Record</title>
</head>
<body>
<form action="E_update.php" method="POST">
<table border="1" cellspacing="0" cellpadding="5">
<tr>
<td><label for="employee_name">Employee Name:</label></td>
<td><input type="text" id="employee_name" name="employee_name" value="<?php echo
$row['employee_name'];?>" required></td>
</tr>
<tr>
<td><label for="gender">Gender:</label></td>
<td><input type="text" id="gender" name="gender" value="<?php echo $row['gender'];?
>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value="<?php echo $row['eid']; ?>"></td><!-- Hidden
input for ID -->
<td colspan="2" align="center">
<input type="submit" name="update" value="update">
</td>
</tr>
<?php
}}
?>
</body>
</html>
Output: -
E_deletedata.php<?
phpinclude
"e_header.php";
$h="Delete Record";
echo '<h4>'.$h.'</h4>';
if(isset($_POST['delete'])
)
{
include "E_config.php";
$_eid=$_POST['id'];
$sql="delete from employe where eid={$_eid}";
$result = mysqli_query($conn,$sql) or die ("query unsuccessfully");
header("Location:http://localhost/meghaphp/ragister/E_index.php");
mysqli_close($conn);
}
?>
<html>
<head>
<title>deleting record</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<table border>
<tr>
</br>
<tr>
<td><label>eid</label></td>
<td><input type="text" name="id"/></td>
</tr>
</br>
</tr>
<tr>
<tdalign="center"><input type="submit" name="delete" value="delete"></td></tr>
</form>
</body></html>
Output: -
Q. Write a php program to create registration and login system.
Code: -
Register.php<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$conn = mysqli_connect("localhost", "root", "", "user_system") or die("Connection
unsuccessful");
$sql = "SELECT * FROM users WHERE username = '{$username}'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$error = "Username already exists!";
}
else
{
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$sql_insert = "INSERT INTO users (username, password) VALUES ('{$username}',
'{$hashed_password}')";
$insert_result = mysqli_query($conn, $sql_insert);
if ($insert_result) {
header("Location: register_success.php?message=Registration successfully! You can now log
in."); exit;
} else {
$error = "Registration failed! Please try again.";
}
}
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register</title>
</head>
<body>
<h2>Register</h2>
<?php if (isset($error)) { echo "<p style='color:red;'>$error</p>"; } ?>
<form method="POST">
<label for="username">Username:</label><br>
<input type="text" name="username" required><br><br>
<label for="password">Password:</label><br>
<input type="password" name="password" required><br><br>
<button type="submit">Register</button>
</form>
<p>Already have an account? <a href="login.php">Login here</a></p>
</body>
</html>
Output: -
Register_success.php
<?php
$message = isset($_GET['message']) ? $_GET['message'] : 'Registration failed. Please try
again.';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0"><title>Registration Successful</title>
</head>
<body>
<h2><?php echo htmlspecialchars($message); ?></h2>
<p><a href="login.php">Login here</a></p>
</body>
</html>
Output: -
Login.php<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$conn = mysqli_connect("localhost", "root", "", "user_system") or die("Connection
unsuccessful");
$sql = "SELECT * FROM users WHERE username = '{$username}'";
$result = mysqli_query($conn,
$sql); if (mysqli_num_rows($result)
> 0) { $user =
mysqli_fetch_assoc($result);
if (password_verify($password, $user['password'])) {
header("Location: dashboard.php?message=Login successfully! Welcome! You have logged
in successfully."); exit;
} else {
$error = "Invalid username or password!";
}
} else {
$error = "Invalid username or password!";
}
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<?php if (isset($error)) { echo "<p style='color:red;'>$error</p>"; } ?>
<form method="POST">
<label for="username">Username:</label><br>
<input type="text" name="username" required><br><br>
<label for="password">Password:</label><br>
<input type="password" name="password" required><br><br>
<button type="submit">Login</button>
</form>
<p>Don't have an account? <a href="register.php">Register here</a></p>
</body>
</html>
Output: -
Dashboard.php
<?php
$message = isset($_GET['message']) ? $_GET['message'] : 'Access Denied: Please log in
first.';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard</title>
</head>
<body>
<h2><?php echo htmlspecialchars($message); ?></h2>
<p><a href="login.php">Log out</a></p>
</body>
</html>
Output: -
Q. Write a PHP program to define class rectangle that has property for length, width
define method of calculate rectangle area and perimeter of it.
Code: - <?php
class
rectangle{
public $lenght,$width,$cal,$pmeter;
function calculate(){
$this->cal=$this->lenght * $this-
>width; echo"Area of rectangle".$this-
>cal; echo"<br>";
$this->pmeter=2*($this->lenght+$this->width);
echo"perimeter of rectangle".$this->pmeter;
}
}
$obj=new rectangle();
$obj->lenght=22;
$obj->width=30;
echo $obj-
>calculate()
?>
Output: -
Q. Write a PHP program to define class employe that extend the person class and add
property like salary and position implement method to display employe.
Code: -
Employee.php<?php
$name,$age;
$this->name = $name;
$this->age = $age;
$this->salary = $salary;
$this->position = $position;
} public function
displayDetails()
$employee->displayDetails();
?>Output:
Q. Write a PHP program to define abstract class shape with an abstract method to
calculate area. Create to subclasses triangle and rectangle that implement abstract
method calculate area method.
Code: - <?
php
abstract class shape{
abstract protected function calArea($b,$he);
}
class triangle extends shape{ public
function calArea($b,$he){
$area=0.5*$b*$he;
echo "Area of triangle=".$area."<br>";
}}
class rectangle extends shape{ public
function calArea($l,$w){
$area1=$l*$w;
echo "Area of rectangle=".$area1;
}
}
$test = new triangle();
$test->calArea(22,22);
$test1 = new rectangle();
$test1->calArea(22,22);
?>
Output: -
Q. Design an MVC application in PHP using Laravel Framework to demonstrate
working of Views and controller.
Code: -
Web.php : To create Route Files: -
<?php
use Illuminate\Support\Facades\
Route; Route::get('/', function ()
{ return view('welcome');
});
Route::get('/about', function ()
{ return view('about');
});
Route::get('/post', function ()
{ return view('post');
});
Create three pages Welcome.blade.php, About.blade.php, Post.blade.php
Welcome.blade.php: -
@include('pages.header')
<article>
<p>Smt. KasturbaiWalchand College of Arts & Science, Sangli, is established on 1960 and
permanently affiliated to Shivaji University, Kolhapur. It is one of the progressively growing
branches of Latthe Education Society, Sangli and imparting knowledge to the masses of the
area. It is established in heritage building with clean and green campus.</p>
</article>
@include('pages.sidebar')
@include('pages.footer')
About.blade.php
@include('pages.header')
<article>
<h1> About Page</h1>
<p>Smt. KasturbaiWalchand College of Arts & Science, Sangli, is established on 1960 and
permanently affiliated to Shivaji University, Kolhapur. It is one of the progressively growing
branches of Latthe Education Society, Sangli and imparting knowledge to the masses of the
area. It is established in heritage building with clean and green campus.</p></article>
@include('pages.sidebar')
@include('pages.footer')
Post.blade.php
@include('pages.header')
<article>
<p>Smt. KasturbaiWalchand College of Arts & Science, Sangli, is established on 1960 and
permanently affiliated to Shivaji University, Kolhapur. It is one of the progressively growing
branches of Latthe Education Society, Sangli and imparting knowledge to the masses of the
area. It is established in heritage building with clean and green campus.</p></article>
@include('pages.sidebar')
@include('pages.footer')
<html>
<head>
<title>Blade Template</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="wrapper">
<header>
</header>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
<a href="/post">Post</a>
</nav>
<main>
</main>
<footer>kwcsangli.in</footer>
</div>
</body>
</html>
Create CSS folder in public folder. Then create style.css to add in the template.
*{ box-sizing: border-
box;
body{
font-family:Arial, Helvetica,sans-
serif; padding:0; margin:0;
wrapper{ width:
1220px; margin: 0
#0000; display:flex;
flex-direction: column;
}
header{ background
: pink; height:80px;
padding:0.15px;
nav{ background:
lightgreen; height:
35px; line-height:
main{
display: flex; }
article{ flex-basis:
900px; padding:
15px; min-height:
600px;
}
aside{ background:
lightgoldenrodyellow; flex-basis:
} footer{ background:
lightgreen; height:
35px; line-height:
Output: -
Home Page
About Page
Post Page
PageController.php
Write code in web.phpuse App\Http\
Controllers\PageController; route::get('/',
[PageController::class,'showUser']);
Execute the code: open terminal -> new terminal type php artisan serve ->copy the IP
Address.
return view('welcome');
{ return
view('User');
Web.php
use App\Http\Controllers\PageController; route::get('/',
[PageController::class,'showHome']); route::get('/user',[PageController::class,'showUser']);
Execute the code: open terminal -> new terminal type php artisan serve ->copy the IP
Address.
CRUD Operations
Create a database and Perform CRUD operations using MVC Framework.
Output:
Output:
Output:
INFO Model [E:\Laravel Project\project-query\app\Models\stud.php] created successfully.
Output:
Output:
Write Code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
$users = DB::table('studs')->get();
//return $users;
//return dd($users);
// foreach($users as $user){
// echo $user->name."<br>";
// }
return view('allstudents',['data'=>$users]);
$users=DB::table('studs')->where('id',$id)-
Illuminate\Support\Facades\Route;
Route::get('/', [UserController::class,'showUsers']);
Route::get('/user/{id}', [UserController::class,'singleUser'])->name('view.user');
Then execute the code php artisan serve and open the IP address in browser
<h3>
{{$user->name}}|
{{$user->email}}|
{{$user->age}}|
{{$user->city}}
</h3>
@endforeach
Execute in browser
userController.php
$users=DB::table('studs')->where('id',$id)-
Allstudent.blade.php
<h1>All Students Data</h1>
<h3>
{{$user->id}}|
{{$user->name}}|
{{$user->email}}|
{{$user->age}}|
{{$user->city}}
<a href="{{route('view.user',$user->id)}}">View</a>
</h3>
@endforeach
$id){ $users=DB::table('studs')->where('id',$id)-
User.blade.php
<h1>User Detail</h1>
<h3>Name:{{$user->name}}</h3>
<h3>Email:{{$user->email}}</h3>
<h3>Age:{{$user->age}}</h3>
<h3>City:{{$user->city}}</h3>
@endforeach
$user=DB::table('studs')
->insert([
'created_at'=>now(),
'updated_at'=>now(),
'name'=>'Krishna',
'email'=>'[email protected]',
'age'=>23,
'city'=>'Pune'
]);
Inserted</h1>";
}
else{ echo "<h1>Data Not
Inserted</h1>";
Output:
To Update File
UserController.phppublic
function updateUser(){
$user=DB::table('studs')
-> where('id',1)
->update([
'city'=>'Mumbai'
]);
if($user){
echo "<h1>Data Successfully Updated</h1>";
}
else{
echo "<h1>Data Not Updated</h1>";
}
Route File Web.php
Route::get('/update', [UserController::class,'updateUser']);
Output:
To Delete A Record
UserController.php
Web.php
Route::get('/delete', [UserController::class,'deleteUser']);
Output: