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

Edited Pr 12

The document outlines a practical exercise for web development using PHP, focusing on error handling and database operations. It includes tasks such as connecting to a database, creating and manipulating a student table, and implementing a simple login system. The objectives, expected outcomes, and necessary skills for students are also detailed, along with examples of PHP scripts for various database operations.

Uploaded by

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

Edited Pr 12

The document outlines a practical exercise for web development using PHP, focusing on error handling and database operations. It includes tasks such as connecting to a database, creating and manipulating a student table, and implementing a simple login system. The objectives, expected outcomes, and necessary skills for students are also detailed, along with examples of PHP scripts for various database operations.

Uploaded by

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

Web Development using PHP (4341604)

Date: _________________
Practical No.12: Error Handling
a. Write a Write a PHP script to connect with database server from
your webpage.
b. Create a database with student table and write a PHP script to
insert a record in student table.
c. Write a program to read student records from student table and
display all these information in table format on output screen.
d. Write a PHP script to delete and update a specific record from
table.
e. Write a PHP script simple login system that allows user to add a
new username if user doesn’t exist in the database, also create a
forgot password link, to redirect user to set up his new password
on authentication.

A. Objective:

When we are talking about creating dynamic website, database plays an very
important role. Students will be able to understand database in phpMyAdmin and can
use various database operations.

B. Expected Program Outcomes (POs)

Basic and Discipline specific knowledge: Apply knowledge of basic mathematics,


science and engineering fundamentals and engineering specialization to solve the
engineering problems.
Problem analysis: Identify and analyse well-defined engineering problems using
codified standard methods.
Design/ development of solutions: Design solutions for engineering well-defined
technical problems and assist with the design of systems components or processes to
meet specified needs.
Engineering Tools, Experimentation and Testing: Apply modern engineering tools
and appropriate technique to conduct standard tests and measurements.
Project Management: Use engineering management principles individually, as a team
member or a leader to manage projects and effectively communicate about well-
defined engineering activities.
Life-long learning: Ability to analyze individual needs and engage in updating in the
context of technological changes in field of engineering.

C. Expected Skills to be developed based on competency:

“Develop a webpage using PHP”


This practical is expected to develop the following skills.
1. Create database and table according to the requirements.

131 | Page
Web Development using PHP (4341604)

2. Develop an application which uses different database operations like insert,


update, delete and select.
3. Follow coding standards and debug program to fix errors.

D. Expected Course Outcomes(Cos)

CO5: Create dynamic web pages using PHP and MySQL database.

E. Practical Outcome(PRo)

Students will be able to use database and perform various database operations using
SQL statements.

F. Expected Affective domain Outcome(ADos)

1) Follow safety practices.


2) Follow Coding standards and practices.
3) Demonstrate working as a leader/ a team member.
4) Follow ethical practices.
5) Maintain tools and equipment.

G. Prerequisite Theory:

Database
Create Database from PhpMyAdmin

132 | Page
Web Development using PHP (4341604)

Create Table from PhpMyAdmin

133 | Page
Web Development using PHP (4341604)

mysqli_connect()
mysqli_connect() is a function used to establish a connection to a MySQL database.

134 | Page
Web Development using PHP (4341604)

Syntax:
mysqli_connect(servername, username, password, dbname);
Here,
servername: specifies the name of the MySQL server host.
username: specifies the username to connect to the MySQL server.
password: specifies the password to connect to the MySQL server.
dbname: specifies the name of the database to connect to.

mysqli_query()
mysqli_query() is a function used in PHP to execute a MySQL query on a database.

Syntax:
mysqli_query(connection, query);
Here,
connection: specifies the MySQL connection to use for the query.
query: specifies the SQL query to be executed.

mysqli_fetch_row()
mysqli_fetch_row() function fetches one row from a result-set and returns it as an
enumerated array. It returns an array of strings that corresponds to the fetched row.

Syntax:
mysqli_fetch_row(result);
Here,
Result: Required. Specifies a result set identifier returned by mysqli_query().

mysqli_fetch_array()
mysqli_fetch_array() function fetches a result row as an associative array, a numeric
array, or both. It returns an array of strings that corresponds to the fetched row.

Syntax:
mysqli_fetch_array(result,resulttype);
Here,
Result: Required. Specifies a result set identifier returned by mysqli_query().
Resulttype: Optional. Specifies what type of array should be produced. Can be one
of the following values: MYSQLI_ASSOC, MYSQLI_NUM, MYSQLI_BOTH (default)

135 | Page
Web Development using PHP (4341604)

mysqli_error()
mysqli_error() function returns the last error description for the most recent function
call, if any.

Syntax:
mysqli_error(connection)
Here,
Connection: Required. Specifies the MySQL connection to use

mysqli_close()
mysqli_close() function closes a previously opened database connection.

Syntax:
mysqli_close(connection)
Here,
Connection: Required. Specifies the MySQL connection to use

Example: (Insert)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', '[email protected]')";

if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

136 | Page
Web Development using PHP (4341604)

H. Resources/Equipment Required

Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
XAMPP server (PHP, Web server, As Per
3 Software Batch Size
Database)
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar

5 Web Browser Edge, Firefox, Chrome or similar

I. Safety and necessary Precautions followed

NA

J. Source code:

A) Write a PHP script to connect with database server from your webpage.
CREATE DATABASE mydatabase;
USE mydatabase;

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) UNIQUE NOT NULL
);

<?php
$servername = "localhost"; // Change if using a remote server
$username = "root"; // Your database username
$password = ""; // Your database password
$database = "mydatabase"; // Your database name

// Create a connection
$conn = new mysqli($servername, $username, $password, $database);

// Check the connection


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully to the database!";


?>
137 | Page
Web Development using PHP (4341604)

A) Input/Output:

Connected successfully to the database!

B) Create a database with student table and write a PHP script to insert a record
in student table.

CREATE DATABASE student_db;


USE student_db;

CREATE TABLE student (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT NOT NULL,
course VARCHAR(50) NOT NULL
);

<?php
$servername = "localhost"; // Change this if using a remote server
$username = "root"; // Your MySQL username
$password = ""; // Your MySQL password
$database = "student_db"; // Database name

// Create a connection
$conn = new mysqli($servername, $username, $password, $database);

// Check the connection


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Insert query
$sql = "INSERT INTO student (name, age, course) VALUES ('John Doe', 20, 'Computer Science')";

// Execute the query


if ($conn->query($sql) === TRUE) {
echo "New record inserted successfully!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close the connection


$conn->close();
?>

138 | Page
Web Development using PHP (4341604)

B) Input/Output:

New record inserted successfully!

C) Write a program to read student records from student table and display all
these information in table format on output screen.

import mysql.connector
from tabulate import tabulate

# Database connection
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)

cursor = conn.cursor()

# Query to fetch student records


cursor.execute("SELECT * FROM student")

# Fetch all records


records = cursor.fetchall()

# Get column names


column_names = [desc[0] for desc in cursor.description]

# Display results in table format


if records:
print(tabulate(records, headers=column_names, tablefmt="grid"))
else:
print("No records found in the student table.")

# Close connection
cursor.close()
conn.close()

139 | Page
Web Development using PHP (4341604)

C) Input/Output:
+---------+---------+-----+------------+-------+
| roll_no | name | age | department | marks |
+---------+---------+-----+------------+-------+
| 101 | Alice | 20 | Computer | 85 |
| 102 | Bob | 21 | Electrical | 78 |
| 103 | Charlie | 19 | Mechanical | 90 |
| 104 | David | 22 | Civil | 76 |
+---------+--------- +-----+------------+-------+

No records found in the student table.

D) Write a PHP script to delete and update a specific record from table.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Update Record
if (isset($_POST['update'])) {
$roll_no = $_POST['roll_no'];
$new_name = $_POST['new_name'];
$new_age = $_POST['new_age'];
$new_department = $_POST['new_department'];
$new_marks = $_POST['new_marks'];

$update_sql = "UPDATE student SET name='$new_name', age=$new_age,


department='$new_department', marks=$new_marks WHERE roll_no=$roll_no";
if ($conn->query($update_sql) === TRUE) {
echo "Record updated successfully!";
} else {
echo "Error updating record: " . $conn->error;
}
}

140 | Page
Web Development using PHP (4341604)

// Delete Record
if (isset($_POST['delete'])) {
$roll_no = $_POST['roll_no'];

$delete_sql = "DELETE FROM student WHERE roll_no=$roll_no";

if ($conn->query($delete_sql) === TRUE) {


echo "Record deleted successfully!";
} else {
echo "Error deleting record: " . $conn->error;
}
}

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
<title>Update & Delete Student Record</title>
</head>
<body>
<h2>Update Student Record</h2>
<form method="post">
Roll No: <input type="number" name="roll_no" required><br>
New Name: <input type="text" name="new_name" required><br>
New Age: <input type="number" name="new_age" required><br>
New Department: <input type="text" name="new_department" required><br>
New Marks: <input type="number" name="new_marks" required><br>
<button type="submit" name="update">Update Record</button>
</form>

<h2>Delete Student Record</h2>


<form method="post">
Roll No: <input type="number" name="roll_no" required><br>
<button type="submit" name="delete">Delete Record</button>
</form>
</body>
</html>

141 | Page
Web Development using PHP (4341604)

D) Input/Output:
Roll No: 101
New Name: Alice Johnson
New Age: 21
New Department: IT
New Marks: 88

Record updated successfully!

Roll No: 102

Record deleted successfully!

E) Write a PHP script simple login system that allows user to add a new username if
user doesn’t exist in the database, also create a forgot password link, to redirect
user to set up his new password on authentication.

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL
);

//dp.php

<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbname = "login_system";

$conn = new mysqli($host, $user, $pass, $dbname);


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>

142 | Page
Web Development using PHP (4341604)

//register.php

<?php
include 'db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$email = $_POST['email'];

$checkUser = $conn->prepare("SELECT * FROM users WHERE username = ?");


$checkUser->bind_param("s", $username);
$checkUser->execute();
$result = $checkUser->get_result();

if ($result->num_rows > 0) {
echo "User already exists!";
} else {
$stmt = $conn->prepare("INSERT INTO users (username, password, email) VALUES (?, ?,
?)");
$stmt->bind_param("sss", $username, $password, $email);
if ($stmt->execute()) {
echo "Registration successful! <a href='login.php'>Login here</a>";
} else {
echo "Error: " . $stmt->error;
}
}
}
?>
<form method="POST">
Username: <input type="text" name="username" required><br>
Email: <input type="email" name="email" required><br>
Password: <input type="password" name="password" required><br>
<button type="submit">Register</button>
</form>

143 | Page
Web Development using PHP (4341604)

//login.php

<?php
include 'db.php';
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];

$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");


$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if ($user && password_verify($password, $user['password'])) {


$_SESSION['user'] = $user['username'];
echo "Login successful! <a href='dashboard.php'>Go to Dashboard</a>";
} else {
echo "Invalid username or password!";
}
}
?>
<form method="POST">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<button type="submit">Login</button>
<a href="forgot_password.php">Forgot Password?</a>
</form>

//forgot_password.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST['email'];

include 'db.php';
$stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
header("Location: reset_password.php?email=" . $email);
exit();
} else {
echo "Email not found!";
}
144 | Page
Web Development using PHP (4341604)

}
}
?>
<form method="POST">
Enter your email: <input type="email" name="email" required><br>
<button type="submit">Reset Password</button>
</form>

//reset_password.php

<?php
if (isset($_GET['email'])) {
$email = $_GET['email'];
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
include 'db.php';
$new_password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$email = $_POST['email'];

$stmt = $conn->prepare("UPDATE users SET password = ? WHERE email = ?");


$stmt->bind_param("ss", $new_password, $email);

if ($stmt->execute()) {
echo "Password reset successfully! <a href='login.php'>Login</a>";
} else {
echo "Error resetting password!";
}
}
?>
<form method="POST">
<input type="hidden" name="email" value="<?php echo $email; ?>">
New Password: <input type="password" name="password" required><br>
<button type="submit">Reset Password</button>
</form>

145 | Page
Web Development using PHP (4341604)

//dashboard.php

<?php
session_start();
if (!isset($_SESSION['user'])) {
header("Location: login.php");
exit();
}
echo "Welcome, " . $_SESSION['user'];
echo "<br><a href='logout.php'>Logout</a>";
?>

//logout.php

<?php
session_start();
session_destroy();
header("Location: login.php");
?>

E) Input/Output:

Registration successful! [Login here]

Login successful! [Go to Dashboard]

Redirects to [email protected]

Password reset successfully! [Login]

Welcome, username
[Logout]

Redirects to login.php
(Session is destroyed)

146 | Page
Web Development using PHP (4341604)

K. Practical related Quiz.

1. To connect with database mysqli_connect() function is used.


2. mysqli_query() function is used to write an SQL statement.
3. To fetch data from database mysqli_fetch_array() and mysqli_fetch_assoc()functions
are used.
4. To get associative type of array in mysqli_fetch_array(), you need to specify
MYSQLI_ASSOC value as an argument.

L. References / Suggestions

1) https://www.w3schools.com/php/default.asp
2) https://www.guru99.com/php-tutorials.html
3) https://www.tutorialspoint.com/php/
4) https://tutorialehtml.com/en/php-tutorial-introduction/
5) www.tizag.com/phpT/
6) https://books.goalkicker.com/PHPBook/
7) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
8) https://codecourse.com/watch/php-basics
9) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview

M. Assessment-Rubrics

Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3

147 | Page

You might also like