Login
Tutorial Login, Register, Logout & CRUD menggunakan PHP & MySQLi OOP + Bootstrap

Tutorial Login, Register, Logout & CRUD menggunakan PHP & MySQLi OOP + Bootstrap

Membuat aplikasi CRUD sederhana menggunakan PHP & MySQLi dengan konsep OOP + tampilan menggunakan Bootstrap. :D
Dulu saya juga sempat share tutorial membuat form login, daftar dan logout dengan 3 pilihan yaitu mysql_connect, mysqli & pdo, namun belum menggunakan OOP.

Awalnya saya cuma iseng-iseng saja membuat aplikasi ini karena sudah lama gak coba bikin CRUD tanpa framework, eh ternyata masih bisa :D
Dari pada mubadzir mending saya share deh di tutorial ini hhe.. Sengaja saya buat sesederhana mungkin biar gampang dimengerti, karena yang paling penting itu faham alur.y bukan syntax.y kalo sudah faham alur.y/logika.y tinggal sobat berekspresi dengan style sobat sendiri :D. Selamat meyimak & semoga bermanfaat.

1. Sobat buat dulu database.y di mysql misal.y dengan nama crud dan table userseperti contoh dibawah:

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `username` varchar(30) NOT NULL,
  `name` varchar(50) NOT NULL,
  `password` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `user`   ADD PRIMARY KEY (`id`); 
ALTER TABLE `user`   MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;


2. Lalu sobat buat folder di htdocs misal.y dengan nama oop, terus buat lagi folder & file di dalam folder oop seperti contoh dibawah:

Di file index.php sobat isi dengan kode berikut:

<?php
// pesan untuk ditampilkan di view $message = "";
// menampilkan nama user yang login $userlogin = "";
session_start(); // jika belum login if(!isset($_SESSION['username'])) {    header('location:login.php');    exit; }
// jika sudah login $userlogin = "<div class='alert alert-info alert-dismissable'>Selamat Datang, <b>{$_SESSION['username']}</b> <a href='logout.php' style='float:right'><b>Logout</b></a></div>";
// load crud.class include_once("app/model/crud.php"); $crud    = new crud();   
// get all user $users   = $crud->execute("SELECT * FROM user"); if(!empty($_POST['username']) && !empty($_POST['name']) && !empty($_POST['password']) && !empty($_POST['act'])){    $name = $_POST['name'];    $username = $_POST['username'];    $password = $_POST['password'];     
   // add user    if($_POST['act'] == 'add'){     
     // cek user      $cek    = $crud->execute("SELECT * FROM user WHERE username = '{$username}'");      if($cek->num_rows != 0) {        $message = "<div class='alert alert-danger alert-dismissable' align='center'>Username Sudah Terdaftar!</div>";
     } else {       
       // save user baru        $add = $crud->execute("INSERT INTO user VALUES (NULL, '{$name}', '{$username}', '{$password}')");        if($add) {          header('location:index.php');          exit;        } else {          $message = "<div class='alert alert-danger alert-dismissable' align='center'>Proses Gagal!</div>";        }      }    }     
   // update user    else if($_POST['act'] == 'update'){      $password_lama = (isset($_POST['password_lama']) ? $_POST['password_lama'] : '');     
     // cek user      $cek    = $crud->execute("SELECT * FROM user WHERE username = '{$username}' AND password = '{$password_lama}'");
     if($cek->num_rows == 0) {        $message = "<div class='alert alert-danger alert-dismissable' align='center'>Password Salah!</div>";
     } else {        $update = $crud->execute("UPDATE user SET name = '{$name}', password = '{$password}' WHERE username = '{$username}'");
       if($update) {          header('location:index.php');
         exit;        } else {          $message = "<div class='alert alert-danger alert-dismissable' align='center'>Proses Gagal!</div>";
       }      }    }else{      header('location:index.php');      exit;    } }   
// hapus user else if(!empty($_GET['id'])){    $deleted    = $crud->execute("DELETE FROM user WHERE id = '{$_GET['id']}'");    if($deleted) {      header('location:index.php');      exit;    } else {      $message = "<div class='alert alert-danger alert-dismissable' align='center'>Proses Gagal!</div>";    } }
// load view include("app/view/header.php"); include("app/view/home.php"); include("app/view/footer.php");

Di file login.php sobat isi dengan kode berikut:

<?php
// pesan untuk ditampilkan di view $message = "";
session_start(); // jika sudah login if(isset($_SESSION['username'])){    header('location:index.php');    exit; }
// jika belum login if(!empty($_POST['username']) && !empty($_POST['password'])){    $username = $_POST['username'];    $password = $_POST['password'];   
   // load crud.class    include_once("app/model/crud.php");    $crud    = new crud();   
   // cek user    $cek   = $crud->execute("SELECT * FROM user WHERE username = '{$username}'");    if($cek->num_rows == 0) {      $message = "<div class='alert alert-danger alert-dismissable' align='center'>Username Belum Terdaftar!</div>";    } else {     
     // menyimpan session user      $login    = $cek->fetch_assoc();      if($password == $login['password']) {        $_SESSION['username'] = $login['username'];        header('location:index.php');        exit;      } else {        $message = "<div class='alert alert-danger alert-dismissable' align='center'>Password salah!</div>";      }    } }
// load view include("app/view/header.php"); include("app/view/login.php"); include("app/view/footer.php");

Di file register.php sobat isi dengan kode berikut:

<?php
// pesan untuk ditampilkan di view $message = "";
session_start(); // jika sudah login if(isset($_SESSION['username'])){    header('location:index.php');    exit; }
// jika belum login if(!empty($_POST['username']) && !empty($_POST['name']) && !empty($_POST['password'])){    $name = $_POST['name'];    $username = $_POST['username'];    $password = $_POST['password'];   
   // load crud.class    include_once("app/model/crud.php");    $crud    = new crud();   
   // cek user    $cek    = $crud->execute("SELECT * FROM user WHERE username = '{$username}'");    if($cek->num_rows != 0) {      $message = "<div class='alert alert-danger alert-dismissable' align='center'>Username Sudah Terdaftar!</div>";
   } else {     
     // save user baru      $register = $crud->execute("INSERT INTO user VALUES (NULL, '{$name}', '{$username}', '{$password}')");
     if($register) {        $message = "<div class='alert alert-success alert-dismissable' align='center'>Pendaftaran Sukses, Silahkan <a href='login.php'>Login</a></div>";
     } else {        $message = "<div class='alert alert-danger alert-dismissable' align='center'>Proses Gagal!</div>";
     }    } }
// load view include("app/view/header.php"); include("app/view/register.php"); include("app/view/footer.php");

Di file logout.php sobat isi dengan kode berikut:

<?php
// menghapus session user session_start(); session_destroy(); header('location: index.php'); exit;

3. Nah di dalam folder asset sobat bikin lagi folder css dan js lalu isi dengan file bootstrap & jQuery, sobat bisa mendownload.y di internet dengan kata kunci cdn bootstrap & jquery. Nanti hasil.y seperti contoh dibawah:


4. Sekarang tinggal folder app, yaitu tempat untuk menyimpan class, view, config dll ala codeigniter :v. Ok langsung saja sobat buat folder dan file di dalam folder app seperti gambar dibawah:

Untuk file .htaccess sobat masukan kode beriku Deny from all tujuan.y supaya semua folder & file yang ada di dalam folder app tidak bisa di akses melalui web browser.


5. Sobat buat file database.php di dalam folder config lalu masukan kode seperti contoh dibawah:

<?php
$hostname   = "localhost"; $username    = "root"; $password    = ""; $database   = "crud";

Sesuaikan dengan akun database sobat.


6. Sobat buat file crud.php di dalam folder model lalu masukan kode seperti contoh dibawah:

<?php
class Crud {   
   function __construct()   {      include('app/config/database.php');   $this->db = new mysqli($hostname, $username, $password, $database);   }   
   function execute($query)    {      $result = $this->db->query($query);      return $result;    }   
}

crud.php adalah sebuah class untuk menjalankan printah query sql.


7. Tadi dibagian awal kan sobat sudah membuat file index.php, login.php, register.php & logout.php yang di dalamnya terdapat perintah load view include('app/view/header.php') dst. Jadi sekarang sobat tinggal buat daftar file di dalam folder view seperti contoh dibawah:

Di file header.php (untuk meta tag, css, js dll) sobat isi dengan kode berikut:

<!DOCTYPE html>
<html>
   <head>     
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />      <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">     
     <!-- Mobile viewport optimized -->      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
     <!-- Title -->      <title>Simple OOP CRUD - iBacor</title>     
     <!-- CSS -->      <link type="text/css" rel="stylesheet" href="asset/css/bootstrap.css" />      <style>      footer {        text-align: center;        position: absolute;        bottom: 0px;        padding: 10px;        display: block;        width: 100%      }      </style>     
     <!-- JS -->      <script type="text/javascript" src="asset/js/jquery.js"></script>      <script type="text/javascript" src="asset/js/bootstrap.js"></script>     
   </head>    <body>

Di file footer.php sobat isi dengan kode berikut:

    <footer>iBacor.com</footer>
   </body>
</html>

Di file register.php (form register) sobat isi dengan kode berikut:

<div class="container-fluid">
   <div class="row">
     <div class="col-md-6 col-md-offset-3">     
       <h1 align="center">Form Register</h1>       
       <form class="form-horizontal" action="register.php" method="post">          <div class="form-group">            <label class="control-label col-sm-2" for="email">Name:</label>            <div class="col-sm-10">              <input type="text" class="form-control" name="name" required>            </div>          </div>          <div class="form-group">            <label class="control-label col-sm-2" for="email">Username:</label>            <div class="col-sm-10">              <input type="text" class="form-control" name="username" required>            </div>          </div>          <div class="form-group">            <label class="control-label col-sm-2" for="pwd">Password:</label>            <div class="col-sm-10">              <input type="password" class="form-control" name="password" required>            </div>          </div>          <div class="form-group">            <div class="col-sm-offset-2 col-sm-10">              <button type="submit" class="btn btn-primary">Register</button>              Sudah Punya akun ? <a href="login.php"><b>Login</b></a>            </div>          </div>        </form>
       <?php echo $message; ?>
     </div>    </div> </div>

Di file login.php (form login) sobat isi dengan kode berikut:

<div class="container-fluid">
   <div class="row">
     <div class="col-md-6 col-md-offset-3">     
       <h1 align="center">Form Login</h1>       
       <form class="form-horizontal" action="login.php" method="post">          <div class="form-group">            <label class="control-label col-sm-2" for="email">Username:</label>            <div class="col-sm-10">              <input type="text" class="form-control" name="username" required>            </div>          </div>          <div class="form-group">            <label class="control-label col-sm-2" for="pwd">Password:</label>            <div class="col-sm-10">              <input type="password" class="form-control" name="password" required>            </div>          </div>          <div class="form-group">            <div class="col-sm-offset-2 col-sm-10">              <button type="submit" class="btn btn-primary">Login</button>              Belum Punya akun ? <a href="register.php"><b>Register</b></a>            </div>          </div>        </form>
       <?php echo $message; ?>
     </div>    </div> </div>

Di file home.php (halaman admin jika sudah login) sobat isi dengan kode berikut:

<div class="container-fluid">
   <div class="row">
     <div class="col-md-6 col-md-offset-3">     
       <h1 align="center">Halaman Admin</h1>
       <?php echo $userlogin; ?>
       <?php echo $message; ?>       
       <table class="table table-striped">          <thead>            <tr>              <th>No</th>              <th>Name</th>              <th>Username</th>              <th style="text-align:right"><button type="button" class="btn btn-success btn-xs" data-toggle="modal" data-target="#addModal">+ Add</button></th>
           </tr>          </thead>          <tbody>         
           <?php            $no = 1;            while($user = $users->fetch_assoc()){              echo '<tr class="users">                  <td>'.$no.'</td>                  <td>'.$user['name'].'</td>                  <td>'.$user['username'].'</td>                  <td align="right">                    <div class="btn-group">                      <button type="button" class="btn btn-danger dropdown-toggle btn-xs"                        data-toggle="dropdown">                        Act <span class="caret"></span>                      </button>                      <ul class="dropdown-menu" role="menu">                        <li><a href="#" data-toggle="modal" data-target="#editModal" data-idx="'. ($no-1) .'" class="edit">Edited</a></li>
                       <li><a href="index.php?id='.$user['id'].'" onClick=\'return confirm("Cius bray?");\'>Deleted</a></li>
                     </ul>
                   </div>                  </td>                </tr>';              $no++;            }            ?>           
         </tbody>        </table>
     </div>    </div> </div>
<!-- Add Modal --> <div id="addModal" class="modal fade" role="dialog">    <div class="modal-dialog">      <div class="modal-content">        <div class="modal-header">          <button type="button" class="close" data-dismiss="modal">&times;</button>          <h4 class="modal-title">Add User</h4>        </div>        <div class="modal-body">          <form class="form-horizontal" action="index.php" method="post">            <div class="form-group">              <label class="control-label col-sm-2">Name:</label>              <div class="col-sm-10">                <input type="text" class="form-control" name="name" required>              </div>            </div>            <div class="form-group">              <label class="control-label col-sm-2">Username:</label>              <div class="col-sm-10">                <input type="text" class="form-control" name="username" required>              </div>            </div>            <div class="form-group">              <label class="control-label col-sm-2">Password:</label>              <div class="col-sm-10">                <input type="password" class="form-control" name="password" required>                <input type="hidden" name="act" value="add" required>              </div>            </div>            <div class="form-group">              <div class="col-sm-offset-2 col-sm-10">                <button type="submit" class="btn btn-primary">Save</button>              </div>            </div>          </form>        </div>      </div>    </div> </div>
<!-- Edit Modal --> <div id="editModal" class="modal fade" role="dialog">    <div class="modal-dialog">      <div class="modal-content">        <div class="modal-header">          <button type="button" class="close" data-dismiss="modal">&times;</button>          <h4 class="modal-title">Edited User</h4>        </div>        <div class="modal-body">          <form class="form-horizontal" action="index.php" method="post">            <div class="form-group">              <label class="control-label col-sm-2">Name:</label>              <div class="col-sm-10">                <input type="text" class="form-control" name="name" id="name" required>              </div>            </div>            <div class="form-group">              <label class="control-label col-sm-2">Username:</label>              <div class="col-sm-10">                <input type="text" class="form-control" name="username" id="username" readonly>              </div>            </div>            <div class="form-group">              <label class="control-label col-sm-2">Password Lama:</label>              <div class="col-sm-10">                <input type="password" class="form-control" name="password_lama" required>                <input type="hidden" name="act" value="update" required>              </div>            </div>            <div class="form-group">              <label class="control-label col-sm-2">Password Baru:</label>              <div class="col-sm-10">                <input type="password" class="form-control" name="password" required>                <input type="hidden" name="act" value="update" required>              </div>            </div>            <div class="form-group">              <div class="col-sm-offset-2 col-sm-10">                <button type="submit" class="btn btn-primary">Update</button>              </div>            </div>          </form>        </div>      </div>    </div> </div>
<script> // memasukan data user ke form yang ada di modal $(document).ready(function(){    $('.edit').click(function () {      // id selector      var ids = $(this).data('idx');     
     // data user      var name = $('.users:eq(' + ids + ') td:eq(1)').html(),        username = $('.users:eq(' + ids + ') td:eq(2)').html();       
     $('#name').val(name);      $('#username').val(username);     
   }); }); </script>

Di file home.php terdapat kode:

<!-- Add Modal -->
<div id="addModal" class="modal fade" role="dialog">
   <div class="modal-dialog">
     <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal">&times;</button>
         <h4 class="modal-title">Add User</h4>
       </div>
       <div class="modal-body">
         <form class="form-horizontal" action="index.php" method="post">
           <div class="form-group">
             <label class="control-label col-sm-2">Name:</label>
             <div class="col-sm-10">
               <input type="text" class="form-control" name="name" required>
             </div>
           </div>
           <div class="form-group">
             <label class="control-label col-sm-2">Username:</label>
             <div class="col-sm-10">
               <input type="text" class="form-control" name="username" required>
             </div>
           </div>
           <div class="form-group">
             <label class="control-label col-sm-2">Password:</label>
             <div class="col-sm-10">
               <input type="password" class="form-control" name="password" required>
               <input type="hidden" name="act" value="add" required>
             </div>
           </div>
           <div class="form-group">
             <div class="col-sm-offset-2 col-sm-10">
               <button type="submit" class="btn btn-primary">Save</button>
             </div>
           </div>
         </form>
       </div>
     </div>
   </div>
</div>

Yaitu modal untuk menampilkan form add user jika tombol add di klick.

dan

<!-- Edit Modal -->
<div id="editModal" class="modal fade" role="dialog">
   <div class="modal-dialog">
     <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal">&times;</button>
         <h4 class="modal-title">Edited User</h4>
       </div>
       <div class="modal-body">
         <form class="form-horizontal" action="index.php" method="post">
           <div class="form-group">
             <label class="control-label col-sm-2">Name:</label>
             <div class="col-sm-10">
               <input type="text" class="form-control" name="name" id="name" required>
             </div>
           </div>
           <div class="form-group">
             <label class="control-label col-sm-2">Username:</label>
             <div class="col-sm-10">
               <input type="text" class="form-control" name="username" id="username" readonly>
             </div>
           </div>
           <div class="form-group">
             <label class="control-label col-sm-2">Password Lama:</label>
             <div class="col-sm-10">
               <input type="password" class="form-control" name="password_lama" required>
               <input type="hidden" name="act" value="update" required>
             </div>
           </div>
           <div class="form-group">
             <label class="control-label col-sm-2">Password Baru:</label>
             <div class="col-sm-10">
               <input type="password" class="form-control" name="password" required>
               <input type="hidden" name="act" value="update" required>
             </div>
           </div>
           <div class="form-group">
             <div class="col-sm-offset-2 col-sm-10">
               <button type="submit" class="btn btn-primary">Update</button>
             </div>
           </div>
         </form>
       </div>
     </div>
   </div>
</div>

Yaitu modal untuk menampilkan form update user jika tombol edited di klick.

<script>
// memasukan data user ke form yang ada di modal
$(document).ready(function(){
   $('.edit').click(function () {
     // id selector 
     var ids = $(this).data('idx');     
     // data user      var name = $('.users:eq(' + ids + ') td:eq(1)').html(),        username = $('.users:eq(' + ids + ') td:eq(2)').html();       
     $('#name').val(name);      $('#username').val(username);     
   }); }); </script>


Kalo sudah sekarang sobat tinggal coba akses website.y :)
Atau sobat juga bisa mendownload aplikasi ini di Github saya.