Implementing CRUD Application in PHP
What is CRUD?
CRUD is an acronym for Create, Read, Update and Delete. CRUD operations are basic data manipulation for database.
In this tutorial we are going to implement queries for the following operations,
such as Create (i.e. insert), Read (i.e. select), Update and Delete operations.
In this tutorial we'll create a simple PHP application to perform all these operations on a MySQL database table in one place.
Well, let's start by creating the table which we'll use in all of our example.
CREATE TABLE users(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
email VARCHAR(255) NOT NULL,
phone VARCHAR(10) NOT NULL
);
To connect to the MySQL database server. Let's create a file named "config.php" and put the following code inside it.
config.php
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'usersdb');
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
To insert records in the users table.
create.php
<?php
require_once "config.php";
if($_SERVER["REQUEST_METHOD"] == "POST"){
$username = $_POST["username"];
$password= $_POST["password"])
$email= $_POST["email"];
$phone= $_POST["phone"];
$sql = "INSERT INTO users(username, password, email, phone) VALUES ('$username', '$password', '$email','$phone')";
$result= mysqli_query($conn, $sql);
echo("Record Added to the Database";
}
mysqli_close($conn);
?>
<!DOCTYPE html>
<html lang="en">
<body>
<h2>Create Record</h2>
<p>Please fill this form and submit to add User record to the database.</p>
<form action="#" method="post">
<label>Username</label>
<input type="text" name="username" >
<label>Password</label>
<input type="text" name="password" >
<label>Email</label>
<input type="text" name="email" >
<label>Phone</label>
<input type="text" name="phone" >
<input type="submit" name="submit: value="Submit">
<a href="index.php">Home</a>
</form>
</body>
</html>
Let's create a file named "read.php" and copy the following code into it. It will reads the records from the users table based the id attribute of the user.
read.php
<?php
if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
require_once "config.php";
$userId = $_GET["id"];
$sql = "SELECT * FROM users WHERE id = ".$userId;
if($stmt = mysqli_prepare($conn, $sql)){
$param_id = trim($_GET["id"]);
$result= mysqli_query($conn, $sql);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$name = $row["username"];
$address = $row["password"];
$salary = $row["email"];
$phone = $row["phone"];
} else{
echo "Oops! Record Not Found.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>View Record</title>
</head>
<body>
<h1>View Record</h1>
<label>Username</label>
<p><?php echo $row["username"]; ?></p>
<label>Password</label>
<p><?php echo $row["password"]; ?></p>
<label>Email</label>
<p><?php echo $row["email"]; ?></p>
<label>Phone</label
<p><?php echo $row["phone"]; ?></p>
<p><a href="index.php"">Back</a></p>
</body>
</html> It will update the existing records in the users table based the id attribute of the user.
update.php
<?php
require_once "config.php";
$username= $password= $email= $phone="";
$username_err = $password_err = $email_err = $phone_err= "";
if(isset($_POST["id"]) && !empty($_POST["id"])){
$id = $_POST["id"];
$input_name = trim($_POST["username"]);
if(empty($input_name)){
$name_err = "Please enter a username.";
} elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$username_err = "Please enter a valid username.";
} else{
$username = $input_name;
}
$input_password = trim($_POST["password"]);
if(empty($input_password )){
$address_err = "Please enter a password.";
} else{
$password= $input_password;
}
$input_email = trim($_POST["email"]);
if(empty($input_email )){
$email_err = "Please enter a email.";
} else{
$email= $input_email;
}
$input_phone = trim($_POST["phone"]);
if(empty($input_phone )){
$address_err = "Please enter a phone number.";
} else{
$password= $input_phone;
}
if(empty($name_err) && empty($password_err) && empty($email_err) && empty($phone_err)){
$sql = "UPDATE users SET username=?, password=?, email=?, phone=? WHERE id=?";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "ssssi", $param_username, $param_password, $param_email, $param_phone, $param_id);
$param_username= $username;
$param_password= $password;
$param_email= $email;
$param_phonephone;
$param_id = $id;
if(mysqli_stmt_execute($stmt)){
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
mysqli_stmt_close($stmt);
}
mysqli_close($link);
} else{
if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
$id = trim($_GET["id"]);
$sql = "SELECT * FROM users WHERE id = ?";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "i", $param_id);
$param_id = $id;
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$username = $row["username"];
$password = $row["password"];
$email = $row["email"]; $phone = $row["phone"];
} else{
header("location: error.php");
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
mysqli_stmt_close($stmt);
mysqli_close($link);
} else{
header("location: error.php");
exit();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update Record</title>
</head>
<body>
<h2>Update Record</h2>
<p>Please edit the input values and submit to update the record.</p>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<label>Username</label>
<input type="text" name="username" value="<?php echo $username; ?>">
<label>Password</label>
<input type="text" name="password" value="<?php echo $password ?>">
<label>Email</label>
<input type="text" name="email" value="<?php echo $email; ?>">
<label>Phone</label>
<input type="text" name="phone" value="<?php echo $phone; ?>">
<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>
</body>
</html>
delete.php
<?php
if(isset($_POST["id"]) && !empty($_POST["id"])){
require_once "config.php";
$userId = $_GET["id"]; // Prepare a delete statement
$sql = "DELETE FROM users WHERE id = = ".$userId;
if($stmt = mysqli_prepare($conn, $sql)){
if(mysqli_stmt_execute($stmt)){
echo "Oops! Record Deleted.";
} else{
echo "Oops! Something went wrong. Please try again later.";
}
mysqli_close($conn);
} else{
if(empty(trim($_GET["id"]))){
echo "does not contains id parameter";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Delete Record</title>
</head>
<body>
<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">
<a href="index.php">No</a>
</p></form>
</body>
</html>
Comments
Post a Comment