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

10.PHP Create, Read, Update, Delete (CRUD)

The document outlines a PHP and MySQL application for managing student and major records using CRUD operations (Create, Read, Update, Delete). It details the database structure, necessary files, and PHP code for connecting to the database, handling data operations, and rendering views with Bootstrap. The application includes forms for adding and editing records, as well as confirmation pages for deletions.

Uploaded by

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

10.PHP Create, Read, Update, Delete (CRUD)

The document outlines a PHP and MySQL application for managing student and major records using CRUD operations (Create, Read, Update, Delete). It details the database structure, necessary files, and PHP code for connecting to the database, handling data operations, and rendering views with Bootstrap. The application includes forms for adding and editing records, as well as confirmation pages for deletions.

Uploaded by

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

Server Side Internet

Programming
Create, Read, Update, Delete using PHP and MySQL
What is CRUD?
CRUD stands for:
- Create
- Read
- Update
- Delete

A usual standard term for managing data in every server side application.
Parts of CRUD
1. List of all records
2. Form to add record
3. Form to edit record
4. Delete record confirmation
5. Form to view record (only read, might need or not)
Preparation
1. Need to create table for Majors
2. Need to create table for Students

Files list:

3. Styling: style.css
4. Header with Bootstrap: header.php
5. Navigation: nav.php
6. Database logic: database.php
7. List of students: index.php
8. List of majors: listMajor.php
9. Student Form for create and update: studentForm.php
10.Major Form for create and update: majorForm.php
11.Deletion confirmation: deleteStudent.php and deleteMajor.php
Table for Major

CREATE TABLE major (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
code CHAR(3)
);
Table for Student

CREATE TABLE student (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
nim CHAR(12),
phone VARCHAR(20),
major_id INT,
FOREIGN KEY (major_id) REFERENCES major(id)
);
Connecting to Database using PDO in database.php
<?php You could try to adapt this file
class DBConnection { to use other database
private $conn; connection methods

public function __construct() {


$this->conn = new PDO(
"mysql:host=localhost;dbname=database",
"username", "password");
}

public function __destruct() {


$this->conn = null;
}
Continuation of database.php queries for student part 2
public function getAllStudents() {
$sql = "SELECT id, name, nim, phone, major_id FROM student";
$result = $this->conn->prepare($sql);
$result->execute();
return $result;
}

public function getStudentById($id) {


$sql = "SELECT id, name, nim, phone, major_id FROM student WHERE id = ?";
$result = $this->conn->prepare($sql);
$result->execute([$id]);
return $result;
}

public function addStudent($name, $nim, $phone, $major_id) {


$sql = "INSERT INTO student (name, nim, phone, major_id)
VALUES (?, ?, ?, ?)";
$result = $this->conn->prepare($sql);
$result->execute([$name, $nim, $phone, $major_id]);
}
Continuation of database.php queries for student part 3
public function updateStudent($id, $name, $nim, $phone, $major_id) {
$sql = "UPDATE student SET name = ?, nim = ?, phone = ?, major_id = ? WHERE id = ?";
$result = $this->conn->prepare($sql);
$result->execute([$name, $nim, $phone, $major_id, $id]);
}

public function deleteStudent($id) {


$sql = "DELETE FROM student WHERE id = ?";
$result = $this->conn->prepare($sql);
$result->execute([$id]);
}
A lot? Yes
We still have queries for major
Continuation of database.php queries for major part 4
public function getAllMajors() {
$sql = "SELECT id, name, code FROM major";
$result = $this->conn->prepare($sql);
$result->execute();
return $result;
}

public function getMajorById($id) {


$sql = "SELECT id, name, code FROM major WHERE id = ?";
$result = $this->conn->prepare($sql);
$result->execute([$id]);
return $result;
}

public function addMajor($name, $code) {


$sql = "INSERT INTO major (name, code) VALUES (?, ?)";
$result = $this->conn->prepare($sql);
$result->execute([$name, $code]);
}
Continuation of database.php queries for major part 5
public function updateMajor($id, $name, $code) {
$sql = "UPDATE major SET name = ?, code = ? WHERE id = ?";
$result = $this->conn->prepare($sql);
$result->execute([$name, $code, $id]);
}

public function deleteMajor($id) {


$sql = "DELETE FROM major WHERE id = ?";
$result = $this->conn->prepare($sql);
$result->execute([$id]);
}
}
Starting the views
Views for CRUD are usually consist of list of records and forms to
add/update records

We have:

1. Form for Students


2. Form for Majors

We will use Bootstrap for the CSS


Header for Bootstrap: header.php
<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
crossorigin="anonymous"></script>
<link href="style.css" rel="stylesheet"/>
</head>
Navigation: nav.php
<?php
require_once("header.php");
?>

<nav class="nav">
<a class="nav-link" href="index.php">Students</a>
<a class="nav-link" href="listMajor.php">Majors</a>
</nav>
Main file for students: index.php
<!DOCTYPE html>
<html lang="en">
<?php include_once("header.php"); ?>
<body>
<?php include_once("nav.php"); ?>
<div class="container mt-3">
<table class="table table-sm table-bordered">
<tr>
<th>Name</th>
<th>NIM</th>
<th>Phone</th>
<th>Major</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<?php
require("database.php");
$db = new DBConnection();
$students = $db->getAllStudents();
Main file for students: index.php (continue)
foreach ($students as $row) {
$major = $db->getMajorById($row['major_id'])->fetch();
?>
<tr>
<td><?= $row["name"]; ?></td>
<td><?= $row["nim"]; ?></td>
<td><?= $row["phone"]; ?></td>
<td><?= $major["name"] ?></td>
<td>
<a class="btn btn-warning" href="studentForm.php?id=<?= $row['id']; ?>">Edit</a>
</td>
<td>
<a class="btn btn-danger" href="deleteStudent.php?id=<?= $row['id']; ?>">Delete</a>
</td>
</tr>
<?php
}
?>
</table>
<div>
<a class="btn btn-success" href="studentForm.php">Add New Data</a>
</div>
</div>
</body>
</html>
List of Students result
Main file for major: listMajor.php
<!DOCTYPE html>
<html lang="en">
<?php include_once("header.php"); ?>
<body>
<?php
require("database.php");
include_once("nav.php");
$db = new DBConnection();
$majors = $db->getAllMajors();
?>
<div class="container mt-3">
<table class="table table-sm table-bordered">
<tr>
<th>Code</th>
<th>Name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
Main file for major: listMajor.php (continuation)
<?php
// loop all majors and show in table
foreach ($majors as $row) {
?>
<tr>
<td><?= $row["code"] ?></td>
<td><?= $row["name"] ?></td>
<td>
<a class="btn btn-warning" href="majorForm.php?id=<?= $row['id'] ?>">Edit</a>
</td>
<td>
<a class="btn btn-danger" href="deleteMajor.php?id=<?= $row['id']?>">Delete</a>
</td>
</tr>
<?php
}
?>
</table>
<div>
<a class="btn btn-success" href="majorForm.php">Add New Data</a>
</div>
</div>
</body>
</html>
List of Majors result
Deletion part: deleteStudent.php
<?php
require_once("header.php");
require_once("database.php");
$db = new DBConnection();
if (isset($_POST["submit"]) and isset($_GET["id"])) {
$db->deleteStudent($_GET["id"]);
header("Location: index.php");
}
?>
<div class="container">
<form action="" method="post">
Are you sure you want to delete this data?<br/>
<input class="mt-3 btn btn-danger" type="submit" name="submit" value="Confirm"/>
<a class="mt-3 btn btn-info" href="listMajor.php">Cancel</a>
</form>
</div>
Deletion part: deleteMajor.php
<?php
require_once("header.php");
require_once("database.php");
$db = new DBConnection();
if (isset($_POST["submit"]) and isset($_GET["id"])) {
$db->deleteMajor($_GET["id"]);
header("Location: listMajor.php");
}
?>
<div class="container">
<form action="" method="post">
Are you sure you want to delete this data?<br/>
<input class="mt-3 btn btn-danger" type="submit" name="submit" value="Confirm"/>
<a class="mt-3 btn btn-info" href="listMajor.php">Cancel</a>
</form>
</div>
Deletion page result
Main part: The Forms
We have 2 forms:

1. Student form
2. Major form
Form: studentForm.php (part 1)
<?php
/**
* Check submit button, take data and save to DB
*/
require_once("header.php");
require_once("database.php");
$db = new DBConnection();
$errors = [];

$majors = $db->getAllMajors()->fetchAll();

// if there is id in the URL, get data


if (isset($_GET["id"])) {
$result = $db->getStudentById($_GET["id"]);
$name = $nim = $phone = $major = "";
if ($result) {
$student = $result->fetch();
$name = $student["name"];
$nim = $student["nim"];
$phone = $student["phone"];
$major = $student["major_id"];
}
}
Form: studentForm.php (part 2)
if (isset($_POST["submit"])) {
// check name first, set error if no value
if (empty($_POST["name"])) {
array_push($errors, "Name is required");
}

if (empty($_POST["nim"])) {
array_push($errors, "NIM is required");
} else {
if (strlen($_POST["nim"]) != 12) {
array_push($errors, "NIM must be exactly 12 characters");
}
}

// save data and go back to index.php (list of students)


$name = $_POST["name"];
$nim = $_POST["nim"];
$phone = $_POST["phone"];
$major = $_POST["major"];

if (count($errors) == 0) {
if (isset($_GET["id"])) {
$db->updateStudent($_GET["id"], $name, $nim, $phone, $major);
} else {
$db->addStudent($name, $nim, $phone, $major);
}
header("Location: index.php");
}
}
?>
Form: studentForm.php (part 3)
<div class="container mt-4">
<form class="form" action="" method="post">
<div class="row mt-3">
<div class="col-4">
<label for="name">Student Name</label>
<input class="form-control" type="text" name="name"
value="<?php echo($name); ?>" placeholder="Enter Student Name"/>
</div>
</div>
<div class="row mt-3">
<div class="col-4">
<label for="nim">Student NIM</label>
<input class="form-control" type="text" name="nim"
value="<?php echo($nim); ?>" placeholder="Enter Student NIM"/>
</div>
</div>
<div class="row mt-3">
<div class="col-4">
<label for="phone">Student Phone</label>
<input class="form-control" type="text" name="phone"
value="<?php echo($phone); ?>"placeholder="Enter Student Phone"/>
</div>
</div>
Form: studentForm.php (part 4)
<div class="row mt-3">
<div class="col-4">
<label for="major">Student Major</label>
<select class="form-select" name="major">
<?php
// NOTE: if the major == $row["id"], put `selected` attribute
foreach ($majors as $row) {
$selected = $row["id"] == $major ? "selected" : "";
echo("<option value=\"{$row['id']}\" {$selected}>"); ← Notice this
echo("{$row['code']} - {$row['name']}");
echo("</option>");
part
}
?>
</select>
</div>
</div>
<input class="mt-3 btn btn-primary" type="submit" name="submit" value="Add Record"/>
<a class="mt-3 btn btn-warning" href="index.php">Cancel</a>
</form>
<div class="mt-4">
<ul class="error">
<?php
foreach ($errors as $err) {
echo("<li>{$err}</li>");
}
?>
</ul>
</div>
</div>
Student Form Result
Form: majorForm.php (part 1)
<?php
/**
* Check submit button, take data and save to DB
*/
require_once("header.php");
require_once("database.php");
$db = new DBConnection();
$errors = [];

// if there is id in the URL, get data


$name = $code = "";
if (isset($_GET["id"])) {
$result = $db->getMajorById($_GET["id"]);
$name = $code = "";
if ($result) {
$major = $result->fetch();
$name = $major["name"];
$code = $major["code"];
}
}
Form: majorForm.php (part 2)
// button is clicked
if (isset($_POST["submit"])) {
// check name first, set error if no value
if (empty($_POST["name"])) {
array_push($errors, "Name is required");
}

if (empty($_POST["code"])) {
array_push($errors, "Code is required");
} else {
if (strlen($_POST["code"]) != 3) {
array_push($errors, "Code must be exactly 3 characters");
}
}

$name = isset($_POST["name"]) ? $_POST["name"] : "";


$code = strtoupper($_POST["code"]);
// check the $errors array, if count is zero, then proceed, else just show errors
if (count($errors) == 0) {
// save data and go back to listMajor.php (list of majors)
// if there is id, we need to update, else create new
if (isset($_GET["id"])) {
$db->updateMajor($_GET["id"], $name, $code);
} else {
$db->addMajor($name, $code);
}
header("Location: listMajor.php");
}
}
?>
Form: majorForm.php (part 3)
<div class="container mt-4">
<form class="form" action="" method="post">
<div class="row mt-3">
<div class="col-4">
<label for="name">Major Name</label>
<input class="form-control" type="text" name="name"
value="<?php echo($name);?>" placeholder="Enter Major Name"/>
</div>
</div>
<div class="row mt-3">
<div class="col-4">
<label for="code">Major Code</label>
<input class="form-control" type="text" name="code"
value="<?php echo($code);?>" placeholder="Enter Major Code"/>
</div>
</div>
<input class="mt-3 btn btn-primary" type="submit" name="submit" value="Save Record"/>
<a class="mt-3 btn btn-warning" href="listMajor.php">Cancel</a>
</form>
<div class="mt-4">
<ul class="error">
<?php
foreach ($errors as $err) {
echo("<li>{$err}</li>");
}
?>
</ul>
</div>
</div>
Major Form Result
Exercise
Try to add another table and create the CRUD model named “Faculty”

Faculty has:

1. ID as primary key
2. Name
3. Code
4. Location

Update your Major table to add column: faculty_id

This is a foreign key to Faculty table


References
https://www.codecademy.com/article/what-is-crud

https://www.freecodecamp.org/news/crud-operations-explained/

https://github.com/williempu/php-crud

You might also like