Edited Pr 12
Edited Pr 12
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.
131 | Page
Web Development using PHP (4341604)
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.
G. Prerequisite Theory:
Database
Create Database from PhpMyAdmin
132 | Page
Web Development using PHP (4341604)
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());
}
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
NA
J. Source code:
A) Write a PHP script to connect with database server from your webpage.
CREATE DATABASE mydatabase;
USE mydatabase;
<?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);
A) Input/Output:
B) Create a database with student table and write a PHP script to insert a record
in student table.
<?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);
// Insert query
$sql = "INSERT INTO student (name, age, course) VALUES ('John Doe', 20, 'Computer Science')";
138 | Page
Web Development using PHP (4341604)
B) Input/Output:
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()
# 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 |
+---------+--------- +-----+------------+-------+
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'];
140 | Page
Web Development using PHP (4341604)
// Delete Record
if (isset($_POST['delete'])) {
$roll_no = $_POST['roll_no'];
$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>
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
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.
//dp.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbname = "login_system";
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'];
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'];
//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'];
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:
Redirects to [email protected]
Welcome, username
[Logout]
Redirects to login.php
(Session is destroyed)
146 | Page
Web Development using PHP (4341604)
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