Skip to main content

PHP Mysql CRUD Operation Example

CRUD(Create, Read, Update, and Delete)

Hi Guys,

Today, In this tutorial you'll give how to build a CRUD application with PHP and MySQL.

What is CRUD

CRUD(Create, Read, Update, and Delete) is an acronym for Create, Read, Update, and Delete. CRUD operations are simply data manipulation for database.In this tutorial we'll create a simple PHP application to perform all these operations on a MySQL database table at one place.

Creating the Database Table

Execute the following SQL query to create a table named users inside your MySQL database. We will use this table for all of our future operations.


CREATE TABLE users (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
fullname VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL,
salary INT(10) NOT NULL
);

Creating the Config File

Database Configurationconfig.php

<?php

/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_NAME', 'php_curd');

/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

?>

Create a file named "index.php" and put the following code in it:

index.php


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="mt-5 mb-3 clearfix">
<h2 class="pull-left">users Details</h2>
<a href="create.php" class="btn btn-success pull-right"><i class="fa fa-plus"></i></a>
</div>
<?php
// Include config file
require_once "config.php";

// Attempt select query execution
$sql = "SELECT * FROM users";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '<table class="table table-bordered table-striped">';
echo "<thead>";
echo "<tr class='bg-dark text-white'>";
echo "<th>#</th>";
echo "<th>FullName</th>";
echo "<th>Email</th>";
echo "<th>Salary</th>";
echo "<th width='22%'>Action</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['fullname'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['salary'] . "</td>";
echo "<td>";
echo '<a href="show.php?id='. $row['id'] .'" class="mr-3 btn btn-success" title="View Record" data-toggle="tooltip"><span class="fa fa-eye"></span></a>';
echo '<a href="update.php?id='. $row['id'] .'" class="mr-3 btn btn-primary" title="Update Record" data-toggle="tooltip"><span class="fa fa-pencil"></span></a>';
echo '<a href="delete.php?id='. $row['id'] .'" title="Delete Record" class="mr-3 btn btn-danger" data-toggle="tooltip"><span class="fa fa-trash"></span></a>';
echo "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo '<div class="alert alert-danger"><em>No records were found.</em></div>';
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}

// Close connection
mysqli_close($link);
?>
</div>
</div>
</div>
</body>
</html>

Creating the Create Page

In this section we'll build the Create functionality of our CRUD application.

Now, Let's create a file named "create.php" and put the following code inside it. It will generate a web form that can be used to insert records in the users table.

create.php

<?php

// Include config file
require_once "config.php";

// Define variables and initialize with empty values
$name = $email = $salary = "";
$name_err = $email_err = $salary_err = "";

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
$input_name = trim($_POST["fullname"]);
if(empty($input_name)){
$name_err = "Please enter a name.";
} elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$name_err = "Please enter a valid name.";
} else{
$name = $input_name;
}

// Validate address
$input_email = trim($_POST["email"]);
if(empty($input_email)){
$email_err = "Please enter an Email.";
} else{
$email = $input_email;
}

// Validate salary
$input_salary = trim($_POST["salary"]);
if(empty($input_salary)){
$salary_err = "Please enter the salary amount.";
} elseif(!ctype_digit($input_salary)){
$salary_err = "Please enter a positive integer value.";
} else{
$salary = $input_salary;
}

// Check input errors before inserting in database
if(empty($name_err) && empty($email_err) && empty($salary_err)){
// Prepare an insert statement
$sql = "INSERT INTO users (fullname, email, salary) VALUES (?, ?, ?)";

if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sss", $param_name, $param_email, $param_salary);

// Set parameters
$param_name = $name;
$param_email = $email;
$param_salary = $salary;

// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records created successfully. Redirect to landing page
header("location: index.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}

// Close statement
mysqli_stmt_close($stmt);
}

// Close connection
mysqli_close($link);
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body class="bg-dark">
<div class="container mt-5">
<div class="row">
<div class="col-md-5 mx-auto">
<div class="card">
<div class="card-header bg-warning">
<h2 class="">Create Record</h2>
</div>
<div class="card-body">
<p>Please fill this form and submit to add user record to the database.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>FullName</label>
<input type="text" name="fullname" class="form-control <?php echo (!empty($name_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $name; ?>">
<span class="invalid-feedback"><?php echo $name_err;?></span>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control <?php echo (!empty($email_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $email; ?>">
<span class="invalid-feedback"><?php echo $email_err;?></span>
</div>
<div class="form-group">
<label>Salary</label>
<input type="text" name="salary" class="form-control <?php echo (!empty($salary_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $salary; ?>">
<span class="invalid-feedback"><?php echo $salary_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
<a href="index.php" class="btn btn-secondary ml-2">Cancel</a>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

Show Data

Now it's time to build the Read functionality of our CRUD application.

Now, Let's create a file named "show.php" and put the following code inside it. It will simply retrieve the records from the users table based the id attribute of the user.

show.php


<?php

// Check existence of id parameter before processing further
if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
// Include config file
require_once "config.php";

// Prepare a select statement
$sql = "SELECT * FROM users WHERE id = ?";

if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);

// Set pg_parameter_status()
$param_id = trim($_GET["id"]);

// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);

if(mysqli_num_rows($result) == 1){
/* Fetch result row as an associative array. Since the result set
contains only one row, we don't need to use while loop */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

// Retrieve individual field value
$name = $row["fullname"];
$address = $row["email"];
$salary = $row["salary"];
} else{
// URL doesn't contain valid id parameter. Redirect to error page
header("location: error.php");
exit();
}

} else{
echo "Oops! Something went wrong. Please try again later.";
}
}

// Close statement
mysqli_stmt_close($stmt);

// Close connection
mysqli_close($link);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>View Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1 class="mt-5 mb-3">View Record</h1>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th width="10%">FullName</th>
<td><?php echo $row["fullname"]; ?></td>
</tr>
<tr>
<th width="10%">Email</th>
<td><?php echo $row["email"]; ?></td>
</tr>
<tr>
<th width="10%">Salary</th>
<td><?php echo $row["salary"]; ?></td>
</tr>
</thead>
</table>
<p><a href="index.php" class="btn btn-primary">Back</a></p>
</div>
</div>
</div>
</body>
</html>
Creating the Update Page

Similarly, we can build the Update functionality of our CRUD application.

Now, Let's create a file named "update.php" and put the following code inside it. It will update the existing records in the users table based the id attribute of the user.

update.php


<?php

// Include config file
require_once "config.php";

// Define variables and initialize with empty values
$name = $email = $salary = "";
$name_err = $email_err = $salary_err = "";

// Processing form data when form is submitted
if(isset($_POST["id"]) && !empty($_POST["id"])){
// Get hidden input value
$id = $_POST["id"];

// Validate name
$input_name = trim($_POST["fullname"]);
if(empty($input_name)){
$name_err = "Please enter a name.";
} elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$name_err = "Please enter a valid name.";
} else{
$name = $input_name;
}

// Validate address address
$input_email = trim($_POST["email"]);
if(empty($input_email)){
$email_err = "Please enter an Email.";
} else{
$email = $input_email;
}

// Validate salary
$input_salary = trim($_POST["salary"]);
if(empty($input_salary)){
$salary_err = "Please enter the salary amount.";
} elseif(!ctype_digit($input_salary)){
$salary_err = "Please enter a positive integer value.";
} else{
$salary = $input_salary;
}

// Check input errors before inserting in database
if(empty($name_err) && empty($email_err) && empty($salary_err)){
// Prepare an update statement
$sql = "UPDATE users SET fullname=?, email=?, salary=? WHERE id=?";

if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sssi", $param_name, $param_email, $param_salary, $param_id);

// Set parameters
$param_name = $name;
$param_email = $email;
$param_salary = $salary;
$param_id = $id;

// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records updated successfully. Redirect to landing page
header("location: index.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}

// Close statement
mysqli_stmt_close($stmt);
}

// Close connection
mysqli_close($link);
} else{
// Check existence of id parameter before processing further
if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
// Get URL parameter
$id = trim($_GET["id"]);

// Prepare a select statement
$sql = "SELECT * FROM users WHERE id = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);

// Set parameters
$param_id = $id;

// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);

if(mysqli_num_rows($result) == 1){
/* Fetch result row as an associative array. Since the result set
contains only one row, we don't need to use while loop */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

// Retrieve individual field value
$name = $row["fullname"];
$email = $row["email"];
$salary = $row["salary"];
} else{
// URL doesn't contain valid id. Redirect to error page
header("location: error.php");
exit();
}

} else{
echo "Oops! Something went wrong. Please try again later.";
}
}

// Close statement
mysqli_stmt_close($stmt);

// Close connection
mysqli_close($link);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body class="bg-dark">
<div class="container mt-5">
<div class="row">
<div class="col-md-5 mx-auto">
<div class="card">
<div class="card-header bg-warning">
<h2 class="">Update Record</h2>
</div>
<div class="card-body">
<p>Please edit the input values and submit to update the user record.</p>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="fullname" class="form-control <?php echo (!empty($name_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $name; ?>">
<span class="invalid-feedback"><?php echo $name_err;?></span>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control <?php echo (!empty($email_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $email; ?>">
<span class="invalid-feedback"><?php echo $email_err;?></span>
</div>
<div class="form-group">
<label>Salary</label>
<input type="text" name="salary" class="form-control <?php echo (!empty($salary_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $salary; ?>">
<span class="invalid-feedback"><?php echo $salary_err;?></span>
</div>
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<input type="submit" class="btn btn-primary" value="Submit">
<a href="index.php" class="btn btn-secondary ml-2">Cancel</a>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

Creating the Delete Page

Finally, we will build the Delete functionality of our CRUD application.

Now, Let's create a file named "delete.php" and put the following code inside it. It will delete the existing records from the users table based the id attribute of the user.

delete.php

<?php

// Process delete operation after confirmation
if(isset($_POST["id"]) && !empty($_POST["id"])){
// Include config file
require_once "config.php";

// Prepare a delete statement
$sql = "DELETE FROM users WHERE id = ?";

if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);

// Set parameters
$param_id = trim($_POST["id"]);

// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records deleted successfully. Redirect to landing page
header("location: index.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}

// Close statement
mysqli_stmt_close($stmt);

// Close connection
mysqli_close($link);
} else{
// Check existence of id parameter
if(empty(trim($_GET["id"]))){
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Delete Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5 mb-3">Delete Record</h2>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="alert alert-danger">
<input type="hidden" name="id" value="<?php echo trim($_GET["id"]); ?>"/>
<p>Are you sure you want to delete this user record?</p>
<p>
<input type="submit" value="Yes" class="btn btn-danger">
<a href="index.php" class="btn btn-secondary">No</a>
</p>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>

Creating the Error Page

At the end, let's create one more file "error.php". This page will be displayed if request is invalid i.e. if id parameter is missing from the URL query string or it is not valid.

error.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5 mb-3">Invalid Request</h2>
<div class="alert alert-danger">Sorry, you've made an invalid request. Please <a href="index.php" class="alert-link">go back</a> and try again.</div>
</div>
</div>
</div>
</div>
</body>
</html>

I will help you..

Comments

Popular posts from this blog

Laravel Scout Algolia Full Text Search Example

Hi Guys Today,I will tell how you can full text search utilizing scout algolia. i will show the example of laravel scout algolia full text search.you can full text search utilizing scout algolia api.it can this example full expound scout algolia full text search. I will show the rudimental step of scout algolia api full text search.if you can utilize full text search for install scout and Algolia api package.we are utilizing algolia api utilizing full text search example in laravel. Here the following steps example laravel full text search Using scout algolia Step 1: Create Laravel Project In this step create laravel project following command. composer create-project --prefer-dist laravel/blog Step 2: Database Configuration After create laravel project , we require to make database configuration, you have to add following details on your .env file. 1.Database Username 1.Database Password 1.Database Name In .env file also available host and port details, you can configu

Laravel IP Address Using Get Location Example

Hi Dev, Today,I will learn you how to get location useing ip address in laravel. we will show example of laravel ip address using get location. you can easy to get location useing ip address in laravel.In this example, I will useing stevebauman/location packege get location useing ip address in laravel. Many time you will need to get visitor's details for security, spam prevention etc. It's very easy to get visitor ip address and their location in PHP Laravel. Step 1: Install stevebauman/location Now, We will install stevebauman/location package using below command.Require this package with composer. It is recommended to only require the package for development. composer require stevebauman/location Step 2: Add providers and aliases In this step,We will add below providers and aliases in the "config/app.php" file. config/app.php 'providers' => [ .... Stevebauman\Location\LocationServiceProvider::class, ], 'aliases' => [ .... 'Loca

Laravel 6 validation required if another field is empty

Hii guys, In this artical, i will give you example of laravel 6 in validation required if another field is empty. We know laravel provide several in-built laravel 6 validation required_without . If you need to add validation rules like required if other field is empty in laravel then you can do it using required_without. I am going to explain you, If you can not enter test (field) value at that time test1 (field) is required. So at that time you can add validation required_without. So, you can use this way: "test1" =>"required_without:test" Example: public function store(Request $request) { $request->validate([ "test" =>"required", "test1" =>"required_without:test" ]); dd("Done!"); } If return validation error otherwise show Done!. It will help you...