Membuat CRUD adalah tugas yang sangat umum dalam pengembangan web (CRUD adalah singkatan dari Create,Read,Update Delete). Jika Anda adalah pengembang web senior, Anda pasti telah menciptakan banyak CRUD. Mungkin ada dalam sistem manajemen konten, sistem manajemen inventori, atau perangkat lunak akuntansi.
Jika Anda baru memulai pengembangan web Atau Baru menggenal PDO atau OOP bisa baca panduannya, Anda pasti akan mengalami banyak karya penciptaan CRUD dalam karir Anda selanjutnya. Tujuan utama CRUD adalah memungkinkan pengguna membuat,membaca ,memperbarui,menghapus data. Biasanya data disimpan di MySQL Database. untuk memulai project CRUD PDO buat dua buah folder dengan nama
config dan layouts didalam folder config buat file database.php dan controller.php, didalam folder layouts buat file header.php dan footer.php
Pertama buat tabel Database
CREATE TABLE `costum_users` (
`id` int(11) NOT NULL,
`first_name` varchar(99) NOT NULL,
`last_name` varchar(99) NOT NULL,
`email` varchar(150) NOT NULL,
`address` varchar(300) NOT NULL,
`modified` datetime NOT NULL,
`updated` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `costum_users`
--
ALTER TABLE `costum_users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `costum_users`
--
ALTER TABLE `costum_users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;
/*!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 */;
lalu buat koneksi database, copas koding dibawah ini paste kedalam file database.php di folder config
/**
* config/database.php
*/
session_start();
date_default_timezone_set("Asia/jakarta");
ini_set('default_charset', 'UTF-8');
error_reporting(E_ALL | E_STRICT);
isset($_SERVER['REMOTE_ADDR']) OR $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
class database
{
private $dsn;
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => 'password',
'database' => 'name database',
'prefix' => '',
'encoding' => 'UTF8',
'port' => '',
);
public function DB()
{
static $instance;
if ($instance === null) {
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => FALSE,
);
$dsn = 'mysql:host=' .$this->default['host'] . ';dbname=' .$this->default['database'] . ';charset=' .$this->default['encoding'];
$instance = new PDO($dsn, $this->default['login'], $this->default['password'], $opt);
}
return $instance;
}
}
masih didalam folder config, copas koding dibawah ini paste kedalam file controller.php
<?php
/**
* class controller.
*/
class ControllerSystem extends database
{
protected $db; //read database
protected $database;
protected $sql;
function __construct()
{
$database = $this->DB();
$this->db = $database;
}
public function insert($ufirst,$ulast,$umail,$uaddress)
{
$sql = "INSERT INTO costum_users SET
first_name=:first_name,
last_name=:last_name,
email=:email,
address=:address";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':first_name', $ufirst, PDO::PARAM_STR);
$stmt->bindParam(':last_name', $ulast, PDO::PARAM_STR);
$stmt->bindParam(':email', $umail, PDO::PARAM_STR);
$stmt->bindParam(':address',$uaddress, PDO::PARAM_STR);
if ($stmt->execute()) {
return TRUE;
}else{
return FALSE;
}
}
public function update($uid,$ufirst, $ulast, $umail, $uaddress)
{
$sql = "UPDATE costum_users SET
first_name=:first_name,
last_name=:last_name,
email=:email,
address=:address
WHERE id=:uid ";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':first_name', $ufirst, PDO::PARAM_STR);
$stmt->bindParam(':last_name', $ulast, PDO::PARAM_STR);
$stmt->bindParam(':email', $umail, PDO::PARAM_STR);
$stmt->bindParam(':address', $uaddress, PDO::PARAM_STR);
$stmt->bindParam(':uid', $uid, PDO::PARAM_INT);
if ($stmt->execute()) {
return TRUE;
}else{
return FALSE;
}
}
public function delete($uid) {
$sql = "DELETE FROM costum_users WHERE id=:uid";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':uid', $uid, PDO::PARAM_INT);
if ($stmt->execute()) {
return TRUE;
}else{
return FALSE;
}
}
public function query($sql) {
$stmt = $this->db->prepare($sql);
$stmt->execute();
return $stmt;
}
public function xss_cleaner($input_str) {
$return_str = str_replace( array('<','>',"'",'"',')','('), array('<','>',''','"',')','('), $input_str );
$return_str = str_ireplace( '%3Cscript', '', $return_str );
return $return_str;
}
##messages
public function messagesin($insert) {
$statusMsg = $insert ?'User data has been inserted successfully.':'Some problem occurred, please try again.';
$msg = $_SESSION['statusMsg'] = $statusMsg;
return $msg;
}
public function messagesup($updated) {
$statusMsg = $updated ?'User data has been updated successfully.':'Some problem occurred, please try again.';
$msg = $_SESSION['statusMsg'] = $statusMsg;
return $msg;
}
public function messagesdel($deleted) {
$statusMsg = $deleted ?'User data has been deleted successfully.':'Some problem occurred, please try again.';
$msg = $_SESSION['statusMsg'] = $statusMsg;
return $msg;
}
public function messageerror() {
$msg = $_SESSION['statusMsg'] = 'Some problem occurred, please try again.';
return $msg;
}
}
selanjutnya buat file index.php untuk kodingnya seperti dibawah ini
<?php
// Path constants
include_once 'config/database.php';//config database
include_once 'config/controller.php';//config database
$systemload = new ControllerSystem();//load controller
include_once 'layouts/header.php';
if (isset($_POST['_publish'])) {
if ($_POST) {
$insert = $systemload->insert($_POST['_tfirst'],$_POST['_tlast'],$_POST['_tmail'],$_POST['_tadress']);
$systemload->messagesin($insert);
}else{
$systemload->messageerror();
}
}
?>
<div class="container-fluid lacodeid-jarak">
<div class="row">
<div class="col-lg-4">
<?php
if(!empty($_SESSION['statusMsg'])){
echo '
<div class="alert alert-success alert-dismissible" role="alert" style="color: #ffffff; background-color: #4caf50;">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Alert</strong> '.$_SESSION['statusMsg'].'
</div><br><br>';
unset($_SESSION['statusMsg']);
}
?>
<div class="panel">
<div class="panel-heading">
<div class="lacode-posisi-text lacodeid-posisi-icon">
<i class="fa fa-size fa-plus lacode-fa"></i>
</div>
<h2>INPUT DATA</h2>
</div>
<div class="panel-body">
<form method="POST">
<div class="form-group">
<input type="text" name="_tfirst" class="form-control" placeholder="first name" required="empty">
</div>
<div class="form-group">
<input type="text" name="_tlast" class="form-control" placeholder="last name" required="empty">
</div>
<div class="form-group">
<input type="email" name="_tmail" class="form-control" placeholder="email" required="empty">
</div>
<div class="form-group">
<textarea class="form-control" name="_tadress" placeholder="address" rows="3" cols="3" required="empty"></textarea>
</div>
<input type="submit" name="_publish" class="btn btn-md btn-primary" value="SUBMIT">
</form>
</div>
</div>
</div>
<div class="col-lg-8">
<div class="panel">
<div class="panel-heading">
<div class="lacode-posisi-text lacodeid-posisi-icon">
<i class="fa fa-size fa-user lacode-fa"></i>
</div>
<h2>DATA USER</h2>
</div>
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Address</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$nomer=0;
$sql = "SELECT `id`, `first_name`, `last_name`, `email`, `address`, `modified`, `updated` FROM `costum_users` ORDER BY id DESC";
$ready = $systemload->query($sql);
foreach ($ready as $key):
$nomer++;
?>
<tr>
<td><?php echo $nomer?></td>
<td><?php echo $key['first_name']?></td>
<td><?php echo $key['last_name']?></td>
<td><?php echo $key['email']?></td>
<td><?php echo $key['address']?></td>
<td>
<a href="update.php?id=<?php echo $key['id']?>" class="btn btn-primary"><i class="fa fa-edit"></i></a>
<a href="delete.php?id=<?php echo $key['id']?>" class="btn btn-danger" onclick="return confirm('hapus data ?')"><i class="fa fa-trash"></i></a>
</td>
</tr>
<?php
endforeach;
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<?php
include_once 'layouts/footer.php';
sebelum lanjut silakan copas koding dibawah ini kedalam file header.php yang berada di folder layouts
<!DOCTYPE html>
<html lang="en">
<head>
<title>CRUD PDO</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css">
<link href="https://fonts.googleapis.com/css?family=Rubik" rel="stylesheet">
<style type="text/css">
body {
font-size: 14px;
font-weight: normal;
background-color: #f5f5f5;
}
.h1, .h2, .h3, h1, h2, h3 {
margin-top: 10px;
margin-bottom: 10px;
}
h2 {
text-align: center;
}
.lacodeid-uppercase {
text-transform: uppercase;
}
.lacodeid-jarak {
margin-top: 115px;
}
.panel-heading {
padding: 0;
}
.style-text {
padding: 0.5em;
font-size: 1em;
margin-bottom: 1.5em;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
border: 1px solid #fb3e08;
border-radius: 1px;
height: 50px;
}
.btn-lacodeid {
width: 120px;
border-radius: 1px;
padding: 10px;
font-size: 14px;
background-color: #fb3e08;
color: #fff !important;
font-weight: bold;
text-transform: uppercase;
overflow: visible;
}
.btn-lacodeid:hover,
.btn-lacodeid:focus{
background-color: #f99f04;
color: #fff !important;
}
.lacode-posisi-text {
text-align: center;
}
.lacodeid-posisi-icon {
margin: -45px 0 0 0;
}
.fa-size {
font-size: 5em;
}
.lacode-fa {
background-color: #fb3e08;
padding: 10px;
border-radius: 50px;
width: 95px;
text-align: center;
color: #fff;
}
.lacodeid-or {
background-color: #fb3e08;
padding: 17px 0;
border-radius: 50px;
width: 70px;
height: 66px;
text-align: center;
color: #fff;
margin: 51px 0 7px 50px;
}
.btn-medsos-lacodeid {
padding: 12px 0;
border-radius: 50px;
width: 56px;
height: 56px;
text-align: center;
color: #fff;
margin: 51px 0 7px 57px;
}
.lacodeid-fb {
background-color: #286090;
}
.lacodeid-gl {
background-color: #d0240b;
}
.lacodeid-tw {
background-color: #0bd0ce;
}
</style>
</head>
<body>
<!-- menu nav -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">CRUD PDO</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Dashboard</a></li>
</ul>
</div>
</div>
</nav>
lalu copas lagi koding dibawah ini kedalam file footer.php yang berada didalam folder layouts
</body>
</html>
sekarang buat file update.php copas koding dibawah ini paste kedalam file update.php
<?php
include_once 'config/database.php';//config database
include_once 'config/controller.php';//config database
$systemload = new ControllerSystem();//load controller
$id = $_GET['id'];
if (isset($_POST['_publish'])) {
if ($_POST) {
$update = $systemload->update($_POST['_tid'],$_POST['_tfirst'],$_POST['_tlast'],$_POST['_tmail'],$_POST['_tadress']);
$systemload->messagesup($update);
}else{
$systemload->messageerror();
}
}
$edit = $systemload->query("SELECT `id`, `first_name`, `last_name`, `email`, `address`, `modified`, `updated` FROM `costum_users` WHERE id='".$id."' LIMIT 1");
$data =$edit->fetch(PDO::FETCH_ASSOC);
include_once 'layouts/header.php';?>
<div class="container-fluid lacodeid-jarak">
<div class="row">
<div class="col-lg-3"></div>
<div class="col-lg-6">
<?php
if(!empty($_SESSION['statusMsg'])){
echo '
<div class="alert alert-success alert-dismissible" role="alert" style="color: #ffffff; background-color: #4caf50;">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Alert</strong> '.$_SESSION['statusMsg'].'
</div><br><br>';
unset($_SESSION['statusMsg']);
}
?>
<div class="panel">
<div class="panel-heading">
<div class="lacode-posisi-text lacodeid-posisi-icon">
<i class="fa fa-size fa-plus lacode-fa"></i>
</div>
<h2>UPDATE DATA</h2>
</div>
<div class="panel-body">
<form method="POST">
<div class="form-group">
<input type="text" name="_tfirst" class="form-control" placeholder="first name" required="empty" value="<?php echo $data['first_name']?>">
</div>
<div class="form-group">
<input type="text" name="_tlast" class="form-control" placeholder="last name" required="empty" value="<?php echo $data['last_name']?>">
</div>
<div class="form-group">
<input type="email" name="_tmail" class="form-control" placeholder="email" required="empty" value="<?php echo $data['email']?>">
</div>
<div class="form-group">
<textarea class="form-control" name="_tadress" placeholder="address" rows="3" cols="3" required="empty"><?php echo $data['address']?></textarea>
</div>
<input type="hidden" name="_tid" value="<?php echo $data['id']?>">
<input type="submit" name="_publish" class="btn btn-md btn-primary" value="SUBMIT">
<a href="index.php" class="btn btn-md btn-success">BACK ADD</a>
</form>
</div>
</div>
</div>
<div class="col-lg-3"></div>
</div>
</div>
<?php
include_once 'layouts/footer.php';
lalu buat file delete.php copas koding dibawah ini kedalam file delete.php
<?php
include_once 'config/database.php';//config database
include_once 'config/controller.php';//config controller
$systemload = new ControllerSystem();//load controller
$id = $_GET['id'];//baca id dikirim
$del = $systemload->delete($id);
$systemload->messagesdel($del);
echo "<script> window.location.assign('index.php'); </script>";
sekian tutorial singkat CRUD menggunakan pdo php. Baca Juga : Load Dinamis File CSS dan JS
Posting Komentar
Posting Komentar