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

PHP Assignments

The document contains multiple PHP programs that demonstrate various functionalities, including calculating the sum of digits of a number, counting vowels in a string, checking voting eligibility, string manipulation, session management for page visits, cookie usage for background color changes, and CRUD operations on a MySQL database. Each program is presented with code snippets and expected outputs. The document serves as a comprehensive guide for PHP programming practices.

Uploaded by

kaverimagdum1101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

PHP Assignments

The document contains multiple PHP programs that demonstrate various functionalities, including calculating the sum of digits of a number, counting vowels in a string, checking voting eligibility, string manipulation, session management for page visits, cookie usage for background color changes, and CRUD operations on a MySQL database. Each program is presented with code snippets and expected outputs. The document serves as a comprehensive guide for PHP programming practices.

Uploaded by

kaverimagdum1101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Q.

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;

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

$digit = (int)$numberStr[$i];

$sum += $digit

if ($digit === 0) {

$countZeros++;

} elseif ($digit % 2 === 0) {

$countEven++;

} else {

$countOdd++;

}
echo "Sum of digits: $sum<br>";

echo "Count of zeros: $countZeros<br>"; echo "Count of

odd digits: $countOdd<br>"; echo "Count of even digits:

$countEven<br>";
}

$number = 123405; analyzeNumber($number);

?>

Output: -

Q. Write a PHP program to calculate number of vowels in string.


Code: - <?php
function countVowels($inputString) {
$vowels = 'aeiouAEIOU';
$count = 0;
for ($i = 0; $i<strlen($inputString); $i++) { if
(strpos($vowels, $inputString[$i]) !== false) {
$count++;
} } return $count;
}
$inputString = "hello word";
$vowelCount = countVowels($inputString);
echo "The number of vowels in the string '{$inputString}' is: $vowelCount\n";
?>
Output: -
Q. Write a PHP program to check if a person is eligible for voting using function.
Code: - <?php
function isEligibleToVote($age) { return $age >= 18;
}
$personAge = 22;
if (isEligibleToVote($personAge)) { echo "The person
is eligible to vote.\n";
} else {
echo "The person is not eligible to vote.\n";
}
?>
Output: -

Q. Write a PHP program to perform the following operations.


a. Transfer String to all uppercase letters.
b. Transfer String to all lowercase letters.
c. Make strings first character in uppercase.
d. Make strings first character of all words in uppercase.
Code: - <?php
function convertToUpper($inputString)
{ returnstrtoupper($inputString);
}
function convertToLower($inputString)
{ returnstrtolower($inputString);
}
function capitalizeFirstCharacter($inputString)
{ returnucfirst($inputString);
}
function capitalizeFirstCharacterOfWords($inputString)
{ returnucwords($inputString);
}
$inputString = "welcome to php"; echo "Original
String: '$inputString'<br>";
echo "All Uppercase: '" .convertToUpper($inputString) . "'<br>"; echo "All
Lowercase: '" .convertToLower($inputString) . "'<br>";
echo "First Character Uppercase: '" .capitalizeFirstCharacter($inputString) . "'<br>";
echo "First Character of All Words Uppercase:
'" .capitalizeFirstCharacterOfWords($inputString) . "'<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>

<form action="E_savedata.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" required></td>

</tr>
<tr>
<tr>

<td><label for="gender">Gender:</label></td>

<td><input type="text" id="gender" name="gender"></td>

</td>

</tr>

</tr>

<tr>

<td colspan="2" align="center">

<input type="submit" name="submit" value="SAVE">

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

class Person { public

$name,$age;

public function construct($name, $age) {

$this->name = $name;

$this->age = $age;

class Employee extends Person { public $salary; public

$position; public function construct($name, $age, $salary,

$position) { parent::construct($name, $age);

$this->salary = $salary;

$this->position = $position;

} public function

displayDetails()

echo "<h1>Employee Details</h1>"."<br>";


echo "<h3>Name: " . $this->name .

"<br>"; echo "Age: " . $this->age . "<br>";

echo "Position: " . $this->position ."<br>";

echo "Salary: $" .$this->salary. "<br>";;

$employee = new Employee("megha", 22, 50000, "web Developer");

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

<h1> Home 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')

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>

<h1> Post 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')

Header.blade.php : To add HTML code for header

<html>

<head>

<title>Blade Template</title>
<link rel="stylesheet" href="css/style.css">

</head>

<body>

<div id="wrapper">

<header>

<h1>Smt. K.W.C. Sangli</h1>

</header>

<nav>
<a href="/">Home</a>

<a href="/about">About</a>

<a href="/post">Post</a>

</nav>

<main>

Footer.blade.php: To add HTML code for footer

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

auto; border:1px solid

#0000; display:flex;

flex-direction: column;

}
header{ background
: pink; height:80px;
padding:0.15px;

nav{ background:

lightgreen; height:

35px; line-height:

35px; padding: 0.15px;

main{

display: flex; }

article{ flex-basis:

900px; padding:

15px; min-height:

600px;

}
aside{ background:

lightgoldenrodyellow; flex-basis:

220px; padding: 22px

} footer{ background:

lightgreen; height:

35px; line-height:

35px; padding: 0.15px;

Output: -

Home Page
About Page

Post Page

Create and write Controller code

Terminal-> new Terminal->php artisan make:ControllerPageController

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.

To display view file in Controller class

PageController extends Controller

public function showHome()


{

return view('welcome');

public function showUser()

{ 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.

PS E:\Laravel Project\project-query>phpartisan make:migrationcreate_studs_table

Output:

INFO Migration [E:\Laravel Project\project-


query\database\migrations/2024_22_20_170922_create_studs_table.php] created successfully.

PS E:\Laravel Project\project-query>php artisan migrate

Output:

INFO Running migrations.

2024_22_20_170922_create_studs_table ...................................................... 28.77ms


DONE

PS E:\Laravel Project\project-query>php artisan make:model stud

Output:
INFO Model [E:\Laravel Project\project-query\app\Models\stud.php] created successfully.

PS E:\Laravel Project\project-query>php artisan migrate:fresh –seed

Output:

Dropping all tables...................................................................... 66.61ms DONE


INFO Preparing database.
Creating migration table ................................................................ 28.50ms DONE
INFO Running migrations.
2024_22_20_170922_create_studs_table ...................................................... 51.42ms
DONE INFO Seeding database.
Database\Seeders\StudSeeder ................................................................... RUNNING
Database\Seeders\StudSeeder ................................................................ 74 ms DONE

Create Controller User Controller


PS E:\Laravel Project\project-query>php artisan make:controllerUserController

Output:

INFO Controller [E:\Laravel Project\project-query\app\Http\Controllers\UserController.php] created


successfully.

Write Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;
class UserController extends Controller

public function showUsers()

$users = DB::table('studs')->get();

//return $users;

//return dd($users);

// foreach($users as $user){

// echo $user->name."<br>";

// }

return view('allstudents',['data'=>$users]);

public function singleUser(string $id){

$users=DB::table('studs')->where('id',$id)-

>get(); return $users;

In Route web.php Write code


<?php

Use App\Http\Controllers\UserController; use

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

Create View File in resources: Allstudents.blade.php


Here controller has send data to view file

<h1>All Students Data</h1>

@foreach ($data as $id => $user )

<h3>

{{$user->name}}|

{{$user->email}}|

{{$user->age}}|

{{$user->city}}
</h3>

@endforeach

Execute in browser

To fetch user input record:


Web.php
Route::get('/user/{id}', [UserController::class,'singleUser'])->name('view.user');

userController.php

public function singleUser(string $id){

$users=DB::table('studs')->where('id',$id)-

>get(); return $users;

Allstudent.blade.php
<h1>All Students Data</h1>

@foreach ($data as $id => $user )

<h3>

{{$user->id}}|

{{$user->name}}|

{{$user->email}}|

{{$user->age}}|

{{$user->city}}

<a href="{{route('view.user',$user->id)}}">View</a>

</h3>

@endforeach

To fetch record from table and show in HTML File

UserController.phppublic function singleUser(string

$id){ $users=DB::table('studs')->where('id',$id)-

>get(); return view('user',['data'=>$users]);

User.blade.php

<h1>User Detail</h1>

@foreach ($data as $id =>$user )

<h3>Name:{{$user->name}}</h3>

<h3>Email:{{$user->email}}</h3>
<h3>Age:{{$user->age}}</h3>

<h3>City:{{$user->city}}</h3>

@endforeach

INSERT UPDATE DELETE Operations


To insert Data in database

userController.php write code :


public function addUser(){

$user=DB::table('studs')

->insert([

'created_at'=>now(),

'updated_at'=>now(),

'name'=>'Krishna',

'email'=>'[email protected]',

'age'=>23,

'city'=>'Pune'

]);

if($user){ echo "<h1>Data Successfully

Inserted</h1>";

}
else{ echo "<h1>Data Not

Inserted</h1>";

Route file web.php


Route::get('/add', [UserController::class,'addUser']);

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:

You might also like