Aplikasi Crud Sederhana Menggunakan PHP MySQL - PDO

//lh4.googleusercontent.com/-eAXyxy2JJKA/AAAAAAAAAAI/AAAAAAAAGS4/OHgzqHzCvtQ/s512-c/photo.jpg
September 28, 2018




Selamat malam sobat kali ini kami akan share bagaimana membuat aplikasi crud basic atau sederhana menggunakan PHP MySQL dan juga bootsrap untuk mempercantik tampilan. Aplikasi dibawah sangat simple dan sangat cocok bagi pemula untuk belajar.



Ada beberapa tahapan yang harus kalian lakukan yang pertama membuat beberapa file yang tentunya mempunyai fungsi yang berbeda, dan pada setiap file kami akan menjelaskannya.

index.php
create.php
delete.php
read.php
update.php
database.php

Tetapi sebelum itu buat database terlebih dahulu dengan nama crud_tutorials kemudian masukkan struktur tabel dibawah ini.

 CREATE TABLE `customers` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `mobile` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;


INSERT INTO `customers` (`id`, `name`, `email`, `mobile`) VALUES
(19, 'ArmanBasir', 'arman@gmail.com', '1234567'),
(20, 'Abidzar', 'abi@gmail.com', '1234578'),
(21, 'Dede Ahmad', 'dede@gmail.com', '12344'),
(22, 'Irsyad Khalid', 'irsyad@gmail.com', '123455'),
(23, 'lawang', 'lawan@gmail.com', '198709');


ALTER TABLE `customers`
  ADD PRIMARY KEY (`id`);


ALTER TABLE `customers`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;
COMMIT; 

index.php

File ini berfungsi menampilkan data user yang ada pada database.

 <!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <link href="css/bootstrap.min.css" rel="stylesheet">
 <script src="js/bootstrap.mid.js"></script>
</head>

<script>
 $(document).ready(function() {
  var table = $('#example').DataTable();
  var tt = new $.fn.dataTable.TableTools( table );
  
  $( tt.fnContainer() ).insertBefore('div.dataTables_wrapper');
 } );
 
</script>

<body>
 <div class="container">
  <div class="row">
  </br>
 </br>
</div>
<div class="row">
 <p>
  <a href ="create.php" button class="btn btn-success">Create</button></a>
  
 </p>
 <table class="table table-striped table-bordered">
  <thead>
   <tr>
    <th>Name</th>
    <th>Email Address</th>
    <th>Mobile Number</th>
    <th>Actions</th>
   </tr>
  </thead>
  <tbody>
   <?php
   include 'database.php';
   $pdo = Database::connect();
   $sql = 'SELECT * FROM customers ORDER BY id DESC';
   foreach ($pdo->query($sql) as $row){
    echo '<tr>';
    echo '<td>'. $row['name'] . '</td>';
    echo '<td>'. $row['email'] . '</td>';
    echo '<td>'. $row['mobile'] . '</td>';
    echo '<td width=250>';
    echo '<a class="btn" href="read.php?id='.$row['id'].'">Info</a>';
    echo '  ';
    echo '<a class="btn btn-success" href="update.php?id='.$row['id'].'">Update</a>';
    echo '  ';
    echo '<a class="btn btn-danger" href="delete.php?id='.$row['id'].'">Delete</a>';
    echo '</td>';
   }
   Database::disconnect();
   ?>
  </tbody>
 </table>
</div>
</body>
</html> 

create.php

File ini mempunyai fungsi menambahkan user atau member baru.

 <?php

require 'database.php';

if ( !empty($_POST)) {
        // keep track validation errors
    $nameError = null;
    $emailError = null;
    $mobileError = null;

        // keep track post values
    $name = $_POST['name'];
    $email = $_POST['email'];
    $mobile = $_POST['mobile'];

        // validate input
    $valid = true;
    if (empty($name)) {
        $nameError = 'Please enter Name';
        $valid = false;
    }

    if (empty($email)) {
        $emailError = 'Please enter Email Address';
        $valid = false;
    } else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
        $emailError = 'Please enter a valid Email Address';
        $valid = false;
    }

    if (empty($mobile)) {
        $mobileError = 'Please enter Mobile Number';
        $valid = false;
    }

    // insert data
    if ($valid) {
        $pdo = Database::connect();
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "INSERT INTO customers (name,email,mobile) values(?, ?, ?)";
        $q = $pdo->prepare($sql);
        $q->execute(array($name,$email,$mobile));
        Database::disconnect();
        header("location: index.php"); 
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap.min.js"></script>
</head>

<body>
    <div class="container">

        <div class="span10 offset1">
            <div class="row">
                <h3>Create Record</h3>
            </div>


            <form class="form-horizontal" action="create.php" method="post">

              <div class="control-group <?php echo !empty($nameError)?'error':'';?>">
                <label class="control-label">Name</label>
                <div class="controls">
                    <input name="name" type="text"  placeholder="Name" value="<?php echo !empty($name)?$name:'';?>">
                    <?php if (!empty($nameError)): ?>
                        <span class="help-inline"><?php echo $nameError;?></span>
                    <?php endif; ?>
                </div>
            </div>

            <div class="control-group <?php echo !empty($emailError)?'error':'';?>">
                <label class="control-label">Email Address</label>
                <div class="controls">
                    <input name="email" type="text" placeholder="Email Address" value="<?php echo !empty($email)?$email:'';?>">
                    <?php if (!empty($emailError)): ?>
                        <span class="help-inline"><?php echo $emailError;?></span>
                    <?php endif;?>
                </div>
            </div>
            <div class="control-group <?php echo !empty($mobileError)?'error':'';?>">
                <label class="control-label">Mobile Number</label>
                <div class="controls">
                    <input name="mobile" type="text"  placeholder="Mobile Number" value="<?php echo !empty($mobile)?$mobile:'';?>">
                    <?php if (!empty($mobileError)): ?>
                        <span class="help-inline"><?php echo $mobileError;?></span>
                    <?php endif;?>
                </div>
            </div>
            <div class="form-actions">
              <button type="submit" class="btn btn-success">Create</button>
              <a class="btn" href="index.php">Back</a>
          </div>
      </form>
  </div>

</div> <!-- /container -->
</body>
</html>
 

delete.php

File ini mempunyai script perintah untuk menghapus data user atau member.

 <?php
require 'database.php';
$id = 0;

if ( !empty($_GET['id'])) {
    $id = $_REQUEST['id'];
}

if ( !empty($_POST)) {
        // keep track post values
    $id = $_POST['id'];
    
        // delete data
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "DELETE FROM customers  WHERE id = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($id));
    Database::disconnect();
    header("Location: index.php");
    
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap.min.js"></script>
</head>

<body>
    <div class="container">
       
        <div class="span10 offset1">
            <div class="row">
                <h3>Delete Record</h3>
            </div>
            
            <form class="form-horizontal" action="delete.php" method="post">
              <input type="hidden" name="id" value="<?php echo $id;?>"/>
              <p class="alert alert-error">Are you sure to delete ?</p>
              <div class="form-actions">
                  <button type="submit" class="btn btn-danger">Yes</button>
                  <a class="btn" href="index.php">No</a>
              </div>
          </form>
      </div>
      
  </div> <!-- /container -->
</body>
</html>
 

read.php

File ini berisi script untuk menampilkan detail user atau member.

 <?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
    $id = $_REQUEST['id'];
}

if ( null==$id ) {
    header("Location: index.php");
} else {
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "SELECT * FROM customers where id = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($id));
    $data = $q->fetch(PDO::FETCH_ASSOC);
    Database::disconnect();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap.min.js"></script>
</head>

<body>
    <div class="container">
       
        <div class="span10 offset1">
            <div class="row">
                <h3>Read Record</h3>
            </div>
            
            <div class="form-horizontal" >
              <div class="control-group">
                <label class="control-label">Name</label>
                <div class="controls">
                    <label class="checkbox">
                        <?php echo $data['name'];?>
                    </label>
                </div>
            </div>
            <div class="control-group">
                <label class="control-label">Email Address</label>
                <div class="controls">
                    <label class="checkbox">
                        <?php echo $data['email'];?>
                    </label>
                </div>
            </div>
            <div class="control-group">
                <label class="control-label">Mobile Number</label>
                <div class="controls">
                    <label class="checkbox">
                        <?php echo $data['mobile'];?>
                    </label>
                </div>
            </div>
            <div class="form-actions">
              <a class="btn" href="index.php">Back</a>
          </div>
          
          
      </div>
  </div>
  
</div> <!-- /container -->
</body>
</html> 

update.php

File ini mempunyai fungsi untuk mengupdate atau mengubah data user atau member.

 <?php
require 'database.php';

$id = null;
if ( !empty($_GET['id'])) {
    $id = $_REQUEST['id'];
}

if ( null==$id ) {
    header("Location: index.php");
}

if ( !empty($_POST)) {
        // keep track validation errors
    $nameError = null;
    $emailError = null;
    $mobileError = null;
    
        // keep track post values
    $name = $_POST['name'];
    $email = $_POST['email'];
    $mobile = $_POST['mobile'];
    
        // validate input
    $valid = true;
    if (empty($name)) {
        $nameError = 'Please enter Name';
        $valid = false;
    }
    
    if (empty($email)) {
        $emailError = 'Please enter Email Address';
        $valid = false;
    } else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
        $emailError = 'Please enter a valid Email Address';
        $valid = false;
    }
    
    if (empty($mobile)) {
        $mobileError = 'Please enter Mobile Number';
        $valid = false;
    }
    
        // update data
    if ($valid) {
        $pdo = Database::connect();
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "UPDATE customers  set name = ?, email = ?, mobile =? WHERE id = ?";
        $q = $pdo->prepare($sql);
        $q->execute(array($name,$email,$mobile,$id));
        Database::disconnect();
        header("Location: index.php");
    }
} else {
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "SELECT * FROM customers where id = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($id));
    $data = $q->fetch(PDO::FETCH_ASSOC);
    $name = $data['name'];
    $email = $data['email'];
    $mobile = $data['mobile'];
    Database::disconnect();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap.min.js"></script>
</head>

<body>
    <div class="container">
       
        <div class="span10 offset1">
            <div class="row">
                <h3>Update Record</h3>
            </div>
            
            <form class="form-horizontal" action="update.php?id=<?php echo $id?>" method="post">
              <div class="control-group <?php echo !empty($nameError)?'error':'';?>">
                <label class="control-label">Name</label>
                <div class="controls">
                    <input name="name" type="text"  placeholder="Name" value="<?php echo !empty($name)?$name:'';?>">
                    <?php if (!empty($nameError)): ?>
                        <span class="help-inline"><?php echo $nameError;?></span>
                    <?php endif; ?>
                </div>
            </div>
            <div class="control-group <?php echo !empty($emailError)?'error':'';?>">
                <label class="control-label">Email Address</label>
                <div class="controls">
                    <input name="email" type="text" placeholder="Email Address" value="<?php echo !empty($email)?$email:'';?>">
                    <?php if (!empty($emailError)): ?>
                        <span class="help-inline"><?php echo $emailError;?></span>
                    <?php endif;?>
                </div>
            </div>
            <div class="control-group <?php echo !empty($mobileError)?'error':'';?>">
                <label class="control-label">Mobile Number</label>
                <div class="controls">
                    <input name="mobile" type="text"  placeholder="Mobile Number" value="<?php echo !empty($mobile)?$mobile:'';?>">
                    <?php if (!empty($mobileError)): ?>
                        <span class="help-inline"><?php echo $mobileError;?></span>
                    <?php endif;?>
                </div>
            </div>
            <div class="form-actions">
              <button type="submit" class="btn btn-success">Update</button>
              <a class="btn" href="index.php">Back</a>
          </div>
      </form>
  </div>
  
</div> <!-- /container -->
</body>
</html>
 

databse.php

File in mempunyai fungsi sebagai koneksi kedatabase.

 <?php
class Database
{
    private static $dbName = 'crud_tutorials' ;
    private static $dbHost = 'localhost' ;
    private static $dbUsername = 'root';
    private static $dbUserPassword = '';

    private static $cont  = null;
     
    public function __construct() {
        die('Init function is not allowed');
    }
     
    public static function connect()
    {
       // One connection through whole application
       if ( null == self::$cont )
       {     
        try
        {
          self::$cont =  new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword); 
        }
        catch(PDOException $e)
        {
          die($e->getMessage()); 
        }
       }
       return self::$cont;
    }
     
    public static function disconnect()
    {
        self::$cont = null;
    }
}
?>
 

Sekian share kali ini silahkan lihat langsung demonya dengan menekan button demo dibawah dan kalian juga bisa langsung mendownload file di atas.

DEMO          DOWNLOAD

Jangan lupa tinggalkan komentar jika masih ada script yang belum anda pahami dan kalian juga bisa request post ataupun project.


Related Post

SUBSCRIBE TO OUR NEWSLETTER

closed