0% found this document useful (0 votes)
409 views12 pages

Crud Tutorial Republic

The document contains PHP code for an employee database management system. It includes SQL code to create an "employees" table with fields for id, name, address, and salary. It also includes PHP files for connecting to the database, displaying employee records in a table, and forms for adding/editing employees. The code allows users to view, add, update and delete employee records from the database.

Uploaded by

Midhun Raj S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
409 views12 pages

Crud Tutorial Republic

The document contains PHP code for an employee database management system. It includes SQL code to create an "employees" table with fields for id, name, address, and salary. It also includes PHP files for connecting to the database, displaying employee records in a table, and forms for adding/editing employees. The code allows users to view, add, update and delete employee records from the database.

Uploaded by

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

Employees.

sql

-- phpMyAdmin SQL Dump


-- version 4.1.14
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: May 16, 2017 at 10:53 AM
-- Server version: 5.6.17
-- PHP Version: 5.5.12

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";


SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;


/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `demo`
--

-- --------------------------------------------------------

--
-- Table structure for table `employees`
--

CREATE TABLE IF NOT EXISTS `employees` (


`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`address` varchar(255) NOT NULL,
`salary` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

--
-- Dumping data for table `employees`
--

INSERT INTO `employees` (`id`, `name`, `address`, `salary`) VALUES


(1, 'Roland Mendel', 'C/ Araquil, 67, Madrid', 5000),
(2, 'Victoria Ashworth', '35 King George, London', 6500),
(3, 'Martin Blank', '25, Rue Lauriston, Paris', 8000);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;


/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

------------------------------------------------------------------------------------------------------------------------
Config.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', 'demo');

/* 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());
}
?>

index.php
<!DOCTYPE html>
<html lang="en">
<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://ajax.googleapis.com/ajax/libs/jquery/1.12.4/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 config file
require_once 'config.php';

// Attempt select query execution


$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: Could not able to execute $sql. " . mysqli_error($link);
}

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

Create.php

<?php
// Include config file
require_once 'config.php';

// Define variables and initialize with empty values


$name = $address = $salary = "";
$name_err = $address_err = $salary_err = "";

// Processing form data when form is submitted


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(trim($_POST["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_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 value.';
} else{
$salary = $input_salary;
}

// Check input errors before inserting in database


if(empty($name_err) && empty($address_err) && empty($salary_err)){
// Prepare an insert statement
$sql = "INSERT INTO employees (name, address, 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_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)){
// Records created successfully. Redirect to landing page
header("location: index.php");
exit();
} else{
echo "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://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<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 this form and submit to add 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"><?php echo $address; ?
></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>
</body>
</html>
Update.php

<?php
// Include config file
require_once 'config.php';

// Define variables and initialize with empty values


$name = $address = $salary = "";
$name_err = $address_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["name"]);
if(empty($input_name)){
$name_err = "Please enter a name.";
} elseif(!filter_var(trim($_POST["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 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($address_err) && empty($salary_err)){
// Prepare an insert statement
$sql = "UPDATE employees SET name=?, address=?, 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_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)){
// Records updated successfully. Redirect to landing page
header("location: index.php");
exit();
} else{
echo "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 employees 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["name"];
$address = $row["address"];
$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://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<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 values 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"><?php echo $address; ?
></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>
</body>
</html>
delete.php

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

// Prepare a select statement


$sql = "DELETE FROM employees 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>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>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h1>Delete Record</h1>
</div>
<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>
</div>
</div>
</div>
</div>
</body>
</html>
error.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 750px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h1>Invalid Request</h1>
</div>
<div class="alert alert-danger fade in">
<p>Sorry, you've made an invalid request. Please <a href="index.php" class="alert-
link">go back</a> and try again.</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

You might also like