English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn how to build CRUD applications using PHP and MySQL.
CRUD isC reate,R ead,U pdate andD The abbreviation for elete. CRUD operations are the basic data operations in a database. In the previous chapters, we have learned how to perform create (i.e., insert), read (i.e., select), update, and delete operations. In this tutorial, we will create a simple PHP application to perform all these operations on a MySQL database table at one place.
Alright, let's start by creating the table, which we will use in all examples.
Execute the following SQL query to create a table namedemployeetable. We will use this table in all operations to come.
CREATE TABLE employees ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100) NOT NULL, address VARCHAR(255) NOT NULL, salary INT(10) NOT NULL );
After creating the table, we need to create a PHP script to connect to the MySQL database server. Let's create a file named "config.php" and place the following code in it.
Later, we will use the PHP require_once() function to include this configuration file in other pages.
<?php /* Database credentials. Assume you are running MySQL Server with default settings (user "root", no password) */ define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_NAME', 'demo'); /* Attempt to connect to the MySQL database */ $link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME); //Check Connection if($link === false){ die("Error: Unable to connect. " . mysqli_connect_error()); } ?>
First, we will create a login page for the CRUD application, which contains a data grid displayingemployeerecords in the database table. It also provides action icons for each record displayed in the grid, allowing you to view details, update, or delete them.
We will also add a create button at the top of the data grid, which can be used toemployeeCreate a new record in the table. Create a file named "index.php" and place the following code in it:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Dashboard</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"> <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.js"></script> <style type="text/css"> .wrapper{ width: 650px; margin: 0 auto; } .page-header h2{ margin-top: 0; } table tr td:last-child a{ margin-right: 15px; } </style> <script type="text/javascript"> $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }); </script> </head> <body> <div class="wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="page-header clearfix"> <h2 class="pull-left">Employees Details</h2> <a href="create.php" class="btn btn-success pull-right">Add New Employee</a> </div> <?php //Include configuration file require_once "config.php"; //Attempt to execute the selection query $sql = "SELECT * FROM employees"; if($result = mysqli_query($link, $sql)){ if(mysqli_num_rows($result) > 0){ echo "<table class='table table-bordered table-striped'>"; echo "<thead>"; echo "<tr>"; echo "<th>#</th>"; echo "<th>Name</th>"; echo "<th>Address</th>"; echo "<th>Salary</th>"; echo "<th>Action</th>"; echo "</tr>"; echo "</thead>"; echo "<tbody>"; while($row = mysqli_fetch_array($result)){ echo "<tr>"; echo "<td>" . $row['id'] . "</td>"; echo "<td>" . $row['name'] . "</td>"; echo "<td>" . $row['address'] . "</td>"; echo "<td>" . $row['salary'] . "</td>"; echo "<td>"; echo "<a href='read.php?id=\". $row['id'] .\"' title='View Record' data-toggle='tooltip'><span class='glyphicon glyphicon}}-eye-open"></span></a>"; echo "<a href='update.php?id=\". $row['id'] .\"' title='Update Record' data-toggle='tooltip'><span class='glyphicon glyphicon}}-pencil"></span></a>"; echo "<a href='delete.php?id=\". $row['id'] .\"' title='Delete Record' data-toggle='tooltip'><span class='glyphicon glyphicon}}-trash'></span></a>"; echo "</td>"; echo "</tr>"; } echo "</tbody>"; echo "</table>"; // Free result set mysqli_free_result($result); } else{ echo "<p class='lead'><em>No records were found.</em></p>"; } } else{ echo "Error: Unable to execute $sql. " . mysqli_error($link); } //Close connection mysqli_close($link); ?> </div> </div> </div> </div> </body> </html>
inemployeesAfter some records are filled in the table, the login page or CRUD data grid may look like the following figure:
Tip:We used the Bootstrap framework to create this CRUD application layout quickly and beautifully. Bootstrap is the most popular and powerful frontend framework for faster and easier web development.
In this section, we will build theC create function.
Let's create a file named "create.php" and place the following code in it. It will generate a web form that can be used toemployeeRecord inserted into the table.
<?php //Include configuration file require_once "config.php"; //Define variables and initialize them with empty values $name = $address = $salary = ""; $name_err = $address_err = $salary_err = ""; //Handle form data when submitting a form if($_SERVER["REQUEST_METHOD"] == "POST"){ // Validate name $input_name = trim($_POST["name"]); 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; } //Verify address $input_address = trim($_POST["address"]); if(empty($input_address)){ $address_err = "Please enter an address."; } else{ $address = $input_address; } //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."; } else{ $salary = $input_salary; } //Check for input errors before inserting into the database if(empty($name_err) && empty($address_err) && empty($salary_err)){ //Prepare INSERT statement $sql = "INSERT INTO employees (name, address, salary) VALUES (?, ?, ?)"; if($stmt = mysqli_prepare($link, $sql)){ //Bind variables as parameters to a prepared statement mysqli_stmt_bind_param($stmt, "sss", $param_name, $param_address, $param_salary); // Set parameters $param_name = $name; $param_address = $address; $param_salary = $salary; // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ //Record created successfully. Redirecting to login page header("location: index.php"); exit(); } else{ There was a problem. Please try again later. } } // Close statement mysqli_stmt_close($stmt); } //Close connection mysqli_close($link); } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> Create Record/title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"> <style type="text/css"> .wrapper{ width: 500px; margin: 0 auto; } </style> </head> <div class="wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="page-header"> <h2>Create Record</h2> </div> <p>Please fill out this form and submit to add an employee record to the database.</p> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <div class="form-group <?php echo (!empty($name_err)) ? 'has-error' : ''; ?>"> <label>Name</label> <input type="text" name="name" class="form-control" value="<?php echo $name; ?>"> <span class="help-block"><?php echo $name_err;?>}}/span> </div> <div class="form-group <?php echo (!empty($address_err)) ? 'has-error' : ''; ?>"> label>Address</label> <textarea name="address" class="form-control/textarea> <span class="help-block"><?php echo $address_err;?></span> </div> <div class="form-group <?php echo (!empty($salary_err)) ? 'has-error' : ''; ?>"> <label>Salary</label> <input type="text" name="salary" class="form-control" value="<?php echo $salary; ?>"> <span class="help-block"><?php echo $salary_err;?></span> </div> <input type="submit" class="btn btn-primary" value="Submit"> <a href="index.php" class="btn btn-default">Cancel</a> </form> </div> </div> </div> </div> </html>
The same "create.php" file will display the HTML form and handle submitted form data. It will also perform basic validation on user input before saving the data.
Now it's time to build the CRUD application'sR ead feature.
Let's create a file named "read.php" and put the following code in it. It will readEmployeethe id attribute from the employees table to retrieve records.
<?php // Check if the id parameter exists before further processing if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){ //Include configuration file require_once "config.php"; //SELECT statement $sql = "SELECT * FROM employees WHERE id = ?"; if($stmt = mysqli_prepare($link, $sql)){ //Bind variables as parameters to a prepared statement mysqli_stmt_bind_param($stmt, "i", $param_id); //Set parameters $param_id = trim($_GET["id"]); //Attempt to execute prepared statement if(mysqli_stmt_execute($stmt)){ $result = mysqli_stmt_get_result($stmt); if(mysqli_num_rows($result) == 1){ /* Extract the result row as an associative array. Since the result set contains only one row, we do not need to use a while loop*/ $row = mysqli_fetch_array($result, MYSQLI_ASSOC); //Search for a single field value $name = $row["name"]; $address = $row["address"]; $salary = $row["salary"]; } else{ //URL does not contain a 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{ //The URL does not contain the id parameter. Redirected to the error page header("location: error.php"); exit(); } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>View Record</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"> <style type="text/css"> .wrapper{ width: 500px; margin: 0 auto; } </style> </head> <div class="wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="page-header"> <h1>View Record</h1> </div> <div class="form-group"> <label>Name</label> <p class="form-control-static"><?php echo $row["name"]; ?></p> </div> <div class="form-group"> label>Address</label> <p class="form-control-static"><?php echo $row["address"]; ?></p> </div> <div class="form-group"> <label>Salary</label> <p class="form-control-static"><?php echo $row["salary"]; ?></p> </div> <p><a href="index.php" class="btn btn-primary">Back</a></p> </div> </div> </div> </div> </html>
Similarly, we can establish our CRUD application UPDATE feature.
Let's create a file named "update.php" and put the following code in it. It will updateEmployeethe id attribute updateEmployeeexisting records in the table.
<?php //Include configuration file require_once "config.php"; //Define variables and initialize them with empty values $name = $address = $salary = ""; $name_err = $address_err = $salary_err = ""; //Handle form data when submitting a form if(isset($_POST["id"]) && !empty($_POST["id"])){ // Get hidden input value $id = $_POST["id"]; // Validate name $input_name = trim($_POST["name"]); 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_address = trim($_POST["address"]); if(empty($input_address)){ $address_err = "Please enter an address."; } else{ $address = $input_address; } //Validate salary $input_salary = trim($_POST["salary"]); if(empty($input_salary)){ $salary_err = "Please enter salary amount."; } elseif(!ctype_digit($input_salary)){ $salary_err = "Please enter a positive integer value."; } else{ $salary = $input_salary; } //Check for input errors before inserting into the database if(empty($name_err) && empty($address_err) && empty($salary_err)){ //UPDATE statement $sql = "UPDATE employees SET name=?, address=?, salary=? WHERE id=?"; if($stmt = mysqli_prepare($link, $sql)){ //Bind variables as parameters to a prepared statement mysqli_stmt_bind_param($stmt, "sssi", $param_name, $param_address, $param_salary, $param_id); //Set parameters $param_name = $name; $param_address = $address; $param_salary = $salary; $param_id = $id; //Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ //Record update successful. Redirect to login page header("location: index.php"); exit(); } else{ echo "There was a problem. Please try again later."; } } // Close statement mysqli_stmt_close($stmt); } //Close connection mysqli_close($link); } else{ //Check if the id parameter exists before further processing if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){ //Retrieve URL parameters $id = trim($_GET["id"]); //select statement $sql = "SELECT * FROM employees WHERE id = ?"; if($stmt = mysqli_prepare($link, $sql)){ //Bind variables as parameters to a prepared statement 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){ /* Extract the result row as an associative array. Since the result set contains only one row, we do not need to use a while loop */ $row = mysqli_fetch_array($result, MYSQLI_ASSOC); //Search for a single field value $name = $row["name"]; $address = $row["address"]; $salary = $row["salary"]; } else{ //The URL does not contain a valid ID. Redirect to the 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{ //The URL does not contain the id parameter. Redirected to the error page header("location: error.php"); exit(); } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Update Record</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"> <style type="text/css"> .wrapper{ width: 500px; margin: 0 auto; } </style> </head> <div class="wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="page-header"> <h2>Update Record</h2> </div> <p>Please edit the input value and submit to update the record.</p> <form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post"> <div class="form-group <?php echo (!empty($name_err)) ? 'has-error' : ''; ?>"> <label>Name</label> <input type="text" name="name" class="form-control" value="<?php echo $name; ?>"> <span class="help-block"><?php echo $name_err;?>}}/span> </div> <div class="form-group <?php echo (!empty($address_err)) ? 'has-error' : ''; ?>"> label>Address</label> <textarea name="address" class="form-control/textarea> <span class="help-block"><?php echo $address_err;?></span> </div> <div class="form-group <?php echo (!empty($salary_err)) ? 'has-error' : ''; ?>"> <label>Salary</label> <input type="text" name="salary" class="form-control" value="<?php echo $salary; ?>"> <span class="help-block"><?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-default">Cancel</a> </form> </div> </div> </div> </div> </html>
Finally, we will builddour CRUD application's delete feature.
Let's create a file named "delete.php" and place the following code inside. It will perform the delete function of our CRUD application based onEmployeeThe id attribute fromEmployeeDelete existing records from the table.
<?php //Confirm and perform the deletion operation if(isset($_POST["id"]) && !empty($_POST["id"])){ //Include configuration file require_once "config.php"; //DELETE statement $sql = "DELETE FROM employees WHERE id = ?"; if($stmt = mysqli_prepare($link, $sql)){ //Bind variables as parameters to a prepared statement 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)){ //Record deleted successfully. Redirected to the login 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 if the id parameter exists if(empty(trim($_GET["id"]))){ //The URL does not contain the id parameter. Redirected to the error page header("location: error.php"); exit(); } } ?> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <div class="alert alert-danger fade in"> <input type="hidden" name="id" value="<?php echo trim($_GET["id"]); ?>"/> <p>Are you sure you want to delete this record?</p><br> <p> <input type="submit" value="Yes" class="btn btn-danger"> <a href="index.php" class="btn btn-default">No</a> </p> </div> </form>
Finally, let's create a file called "error.php". If the request is invalid, i.e., the id parameter is missing from the URL query string or the parameter is invalid, this page will be displayed.
<h1>Invalid request</h1> <div class="alert alert-danger fade in"> <p>Sorry, the request you made is invalid. Please <a href="index.php" class="alert-link">Return</a> Try again later.</p> </div>
After a long journey, we finally completed the CRUD application using PHP and MySQL.