CRUD is an acronym for Create, Read, Update, and Delete. As the name suggests, these operations manipulate data in a database that is important to any web application’s basic functionality. We can create a PHP application coupled with a MySQL database to perform these operations.
We will create a sample database and then create a table inside it named data. The elements will be simple, including a name
, id
, and address
.
CREATE TABLE data (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
address VARCHAR(255) NOT NULL,
);
We will create a landing page through a PHP file, where we will perform the CRUD operations. We name this file index.php
. The following code will create a simple landing page that saves the name
and address
of a user.
<!DOCTYPE html><html><head><title>CRUD: Create, Update, Delete PHP MySQL</title></head><body><form method="post" action="server.php" ><div class="input-group"><label>Name</label><input type="text" name="name" value=""></div><div class="input-group"><label>Address</label><input type="text" name="address" value=""></div><div class="input-group"><button class="btn" type="submit" name="save" >Save</button></div></form></body></html>
We will now create a configuration file config.php
that will connect with the database server.
<?phpsession_start();$db = mysqli_connect('localhost', 'root', '', 'sample');// initializing variables$name = "";$address = "";$id = 0;$update = false;if (isset($_POST['save'])) {$name = $_POST['name'];$address = $_POST['address'];mysqli_query($db, "INSERT INTO data (name, address) VALUES ('$name', '$address')");$_SESSION['message'] = "Address saved";header('location: index.php');}
Add this file in the index.php
file by writing this statement at the top:
<?php include('server.php'); ?>
Until this point, we have connected with the database, initialized the variables name
and address
, and stored them in the database. We are done with the Create part of CRUD. Now, we can move on to reading the contents of the database records.
In order to read the data stored in the database, we will retrieve the information from the database records and display them using the following code:
<?php $results = mysqli_query($db, "SELECT * FROM data"); ?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th colspan="2">Action</th>
</tr>
</thead>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['address']; ?></td>
<td>
<a href="index.php?edit=<?php echo $row['id']; ?>" class="edit_btn" >Edit</a>
</td>
<td>
<a href="server.php?del=<?php echo $row['id']; ?>" class="del_btn">Delete</a>
</td>
</tr>
<?php } ?>
</table>
<form>
You can copy-paste this code above the input form in index.php
, and the contents of the database will be displayed.
Credits:
Free Resources