PHP MySql CRUD Dengan Konsep MVC

Pada postingan kali ini saya akan sharing cara membuat CRUD dengan php menggunakan konsep MVC, ok langsung saja buka code editor (saya menggunakan sublime text) dan buat folder baru dengan nama phpmvc didalam folder htdocs kalian dan tambah folder seperti berikut : 



Setelah itu kita siapkan database di mysql, buat database dengan nama phpmvc dan tablenya seperti gambar berikut :



tambahkan file config.php didalam folder app/config :


<?php

define('BASEURL', 'http://localhost:8181/phpmvc/public');
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'phpmvc');

kemudian tambahkan 3 file controller didalam folder app/controllers, yaitu Home, About, dan Mahasiswa :

Home.php

<?php

class Home extends Controller {
public function index()
{
$data['nama'] = $this->model('User_model')->getUser();
$data['title'] = 'Halaman Home';

$this->view('templates/header', $data);
$this->view('home/index', $data);
$this->view('templates/footer');
}

}

About.php

<?php

class About extends Controller{

public function index($nama = 'bejo', $pekerjaan = 'guru'){
$data['title'] = 'Halaman About';
$this->view('templates/header', $data);
$this->view('about/index');
$this->view('templates/footer');
}

}

Mahasiswa.php

<?php

class Mahasiswa extends Controller {
public function index(){
$data['title'] = 'Data Mahasiswa';
$data['mhs'] = $this->model('Mahasiswa_model')->getAllMhasiswa();
$this->view('templates/header', $data);
$this->view('mahasiswa/index', $data);
$this->view('templates/header');
}

public function detail($id){

$data['title'] = 'Detail Mahasiswa';
$data['mhs'] = $this->model('Mahasiswa_model')->getAllMhasiswaById($id);
$this->view('templates/header', $data);
$this->view('mahasiswa/detail', $data);
$this->view('templates/header');
}

public function edit($id){

$data['title'] = 'Detail Mahasiswa';
$data['mhs'] = $this->model('Mahasiswa_model')->getAllMhasiswaById($id);
$this->view('templates/header', $data);
$this->view('mahasiswa/edit', $data);
$this->view('templates/header');
}

public function tambah(){
$data['title'] = 'Tambah Mahasiswa';
$this->view('templates/header', $data);
$this->view('mahasiswa/tambah');
$this->view('templates/header');
}

public function simpanmahasiswa(){
$nim     = $_POST['nim'];
$nama    = $_POST['nama'];
$jurusan = $_POST['jurusan'];
$data['mhs'] = $this->model('Mahasiswa_model')->tambahMahasiswa($nim,$nama,$jurusan);
// return $this->index();
header('location:../mahasiswa');
}

public function updateMahasiswa(){
$nim     = $_POST['nim'];
$nama    = $_POST['nama'];
$jurusan = $_POST['jurusan'];
$data['mhs'] = $this->model('Mahasiswa_model')->updateMahasiswa($nim,$nama,$jurusan);
// return $this->index();
header('location:../mahasiswa');
}

public function hapus($id){
$data['mhs'] = $this->model('Mahasiswa_model')->deleteMhs($id);
// return $this->index();
header('location:../../mahasiswa');
}
}

Tambah 3 file didalam folder app/core : App.php, Controller.php, Database.php

App.php

<?php

class App{

protected $controller = 'Home';
protected $method = 'index';
protected $params = [];

public function __construct(){
$url = $this->parseURL();

if(file_exists('../app/controllers/' . $url[0] . '.php')){
$this->controller = $url[0];
unset($url[0]);
}

require_once '../app/controllers/' . $this->controller . '.php';
$this->controller = new $this->controller;

if(isset($url[1])){
if(method_exists($this->controller, $url[1])){
$this->method = $url[1];
unset($url[1]);
}
}

if(!empty($url)){
$this->params = array_values($url);
}

//jalankan controller
call_user_func_array([$this->controller, $this->method], $this->params);
}

public function parseURL(){
if( isset($_GET['url'])){
$url = rtrim($_GET['url'], '/');
$url = filter_var($url, FILTER_SANITIZE_URL);
$url = explode('/',$url);
return $url;
}
}

}

Controller.php

<?php

class Controller{
public function view($view, $data = [])
{
require_once '../app/views/' . $view . '.php';
}

public function model($model)
{
require_once '../app/models/' . $model . '.php';
return new $model;
}

}

Database.php

<?php

class Database{
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbnm = DB_NAME;

private $dbh;
private $stmt;

public function __construct()
{
$dsn = 'mysql:host='. $this->host .';dbname='. $this->dbnm;

$option = [
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
];

try{
$this->dbh = new PDO($dsn,$this->user,$this->pass, $option);
}catch(PDOException $e){
die($e->getMessage());
}
}


public function query($query)
{
$this->stmt = $this->dbh->prepare($query);
}

public function bind($param, $value, $type = null){
if(is_null($type)){
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}

$this->stmt->bindValue($param, $value, $type);
}

public function execute()
{
$this->stmt->execute();
}

public function resultSet()
{
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}

public function single()
{
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
}



tambahkan model didalam folder models : Mahasiswa_model.php

<?php

class Mahasiswa_model{

private $table = 'mahasiswa';
private $db;

public function __construct()
{
$this->db = new Database;
}

public function getAllMhasiswa()
{
$this->db->query('SELECT * FROM ' . $this->table);
return $this->db->resultSet();
}

public function getAllMhasiswaById($id)
{
$this->db->query('SELECT * FROM ' . $this->table . ' WHERE id=:id');
$this->db->bind('id',$id);
return $this->db->single();
}

public function tambahMahasiswa($nim, $nama, $jurusan)
{
$this->db->query('INSERT INTO ' . $this->table . '(nim, nama, jurusan) VALUES(:nim, :nama, :jurusan)');
$this->db->bind('nim',$nim);
$this->db->bind('nama',$nama);
$this->db->bind('jurusan',$jurusan);
$this->db->execute();
}

public function updateMahasiswa($nim, $nama, $jurusan)
{
$this->db->query('UPDATE ' . $this->table . ' SET nama=:nama, jurusan=:jurusan WHERE nim=:nim');
$this->db->bind('nim',$nim);
$this->db->bind('nama',$nama);
$this->db->bind('jurusan',$jurusan);
$this->db->execute();
}

public function deleteMhs($id)
{
$this->db->query('DELETE FROM ' . $this->table . ' WHERE id=:id');
$this->db->bind('id',$id);
$this->db->execute();
}

}

didalam folder view tambahkan folder untuk masing-masing controller yaitu : folder home, about, mahasiswa dan satu foder tambahan yaitu templates 
didalam folder templates tambahkan dua file : header.php dan footer.php

header.php

<!DOCTYPE html>
<html>
<head>
<title><?= $data['title']; ?></title>
<link rel="stylesheet" href="<?= BASEURL; ?>/css/bootstrap.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
  <a class="navbar-brand" href="<?= BASEURL; ?>">Toekang Ketik</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
    <div class="navbar-nav">
      <!-- <a class="nav-item nav-link active" href="<?= BASEURL; ?>">Home <span class="sr-only">(current)</span></a> -->
      <a class="nav-item nav-link" href="<?= BASEURL; ?>/mahasiswa">Mahasiswa</a>
      <a class="nav-item nav-link" href="<?= BASEURL; ?>/about">About Me</a>
      
    </div>
  </div>
  </div>

</nav>

footer.php

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="<?= BASEURL; ?>/js/bootstrap.js"></script>
</body>

</html>

pada folder home tambahkan file index.php :

<div class="container mt-3">
<div class="jumbotron">
<h1 class="display-4">Belajar PHP MVC</h1>
<p class="lead">This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
<hr class="my-4">
<p>It uses utility classes for typography and spacing to space content out within the larger container.</p>
<a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
</div>

</div>

pada folder about juga tambahkan file index.php

<div class="container mt-3">
<div class="jumbotron jumbotron-fluid">
<div class="container" align="center">
<h1 class="display-4">About Me</h1>
<img src="<?= BASEURL ?>/img/husnulm.jpg" alt="Husnul M" width="200" height="250" class="rounded-circle shadow">

<p class="lead">
</p>
<table>
<tr>
<td>Nama Saya</td><td> : </td>
<td>Husnul Mub</td>
</tr>
<tr>
<td>Pekerjaan</td><td> : </td>
<td>SAP ABAP Consultant</td>
</tr>
</table>
</div>
</div>

</div>

kemudian didalam folder mahasiswa tambahkan file : index.php, detail.php, tambah.php dan edit.php 

index.php

<div class="container mt-3">
<div class="row">
<div class="col-12">
<h1>Data Mahasiswa</h1>
<ul class="list-group">
<table class="table table-stripped">
<thead>
<tr>
<th scope="col">Nama</th>
<th scope="col" width="200px">Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($data['mhs'] as $mhs) :?>
<tr>
<td><?= $mhs['nama'];?></td>
<td>
<a href="<?= BASEURL; ?>/mahasiswa/detail/<?= $mhs['id'] ?>" class="badge badge-primary badge-pill">Detail</a>

<a href="<?= BASEURL; ?>/mahasiswa/edit/<?= $mhs['id'] ?>" class="badge badge-primary badge-pill">Edit</a>
<a href="<?= BASEURL; ?>/mahasiswa/hapus/<?= $mhs['id'] ?>" class="badge badge-primary badge-pill">Hapus</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</ul>
<a href="<?= BASEURL; ?>/mahasiswa/tambah" class="btn btn-success mt-2">Tambah Mahasiswa</a>
</div>
</div>
</div>

detail.php

<div class="container mt-3">
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="<?= BASEURL ?>/img/husnulm.jpg" alt="Card image cap">
<div class="card-body">
<h5 class="card-title"><?= $data['mhs']['nama']; ?></h5>
<p class="card-text"><?= $data['mhs']['jurusan']; ?></p>
<a href="<?= BASEURL; ?>/mahasiswa" class="btn btn-primary">Kembali</a>
</div>
</div>

</div>

tambah.php

<div class="container mt-3">
<form action="<?= BASEURL; ?>/mahasiswa/simpanmahasiswa" method="POST" enctype="multipart/form-data">
<input class="form-control form-control-lg mt-2" type="text" name="nim" placeholder="NIM">
<input class="form-control form-control-lg mt-2" type="text" name="nama" placeholder="Nama">
<input class="form-control form-control-lg mt-2" type="text" name="jurusan" placeholder="Jurusan">
<input type="submit" value="simpan" class="btn btn-success mt-2">
<a href="<?= BASEURL; ?>/mahasiswa" class="btn btn-primary mt-2">Kembali</a>
</form>

</div>

edit.php

<div class="container mt-3">
<form action="<?= BASEURL; ?>/mahasiswa/updateMahasiswa" method="POST" enctype="multipart/form-data">
<input class="form-control form-control-lg mt-2" type="text" readonly="true" name="nim" placeholder="NIM" value="<?= $data['mhs']['nim']; ?>">
<input class="form-control form-control-lg mt-2" type="text" name="nama" placeholder="Nama" value="<?= $data['mhs']['nama']; ?>">
<input class="form-control form-control-lg mt-2" type="text" name="jurusan" placeholder="Jurusan" value="<?= $data['mhs']['jurusan']; ?>">
<input type="submit" value="simpan" class="btn btn-success mt-2">
<a href="<?= BASEURL; ?>/mahasiswa" class="btn btn-primary mt-2">Kembali</a>
</form>
</div>

kemudian tambah file init.php dan .htaccess didalam folder app

init.php

<?php

require_once 'core/App.php';
require_once 'core/Controller.php';
require_once 'core/Database.php';

require_once 'config/config.php';

.htaccess

Options -Indexes


kemudian pada folder public folder css dan js berisi bootstrap, silahkan di dowload di website bootstrap dan didalam folder img bisa kalian tambahkan image terserah teman2 mau pakai image apa saja dan tambah file index dan .htaccess


index.php

<?php

require_once '../app/init.php';


$app = new App;

.htaccess

Options -Multiviews

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f


RewriteRule ^(.*)$ index.php?url=$1 [L]


ok sudah selesai dan berikut hasilnya :













ok semoga bermanfaat :D



sumber : 
https://www.youtube.com/watch?v=tBKOb8Ib5nI&list=PLFIM0718LjIVEh_d-h5wAjsdv2W4SAtkx

https://www.facebook.com/WebProgrammingUNPAS/

Comments

  1. Gan, kok gagal terus ya?

    Warning: require_once(../app/models/User_model.php): failed to open stream: No such file or directory in C:\xampp\htdocs\phpmvc\app\core\Controller.php on line 11

    Fatal error: require_once(): Failed opening required '../app/models/User_model.php' (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\phpmvc\app\core\Controller.php on line 11

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. itu User_model.php nya belum ada, coba download source code nya disini gan

      https://github.com/HusnulM/phpmvc

      Delete
    3. coba cek baseurl di dalam folder config/config.php

      Delete
  2. Replies
    1. Coba cek baseurl di dalam folder app/config/config.php

      Delete
  3. This comment has been removed by the author.

    ReplyDelete
  4. saya coba programnya tapi ada yang error
    Notice: Trying to access array offset on value of type null in C:\xampp\htdocs\phpmvc\app\core\App.php on line 12

    ReplyDelete
  5. require_once(../app/models/registrasi_model.php): failed to open stream: No such file or directory


    require_once(): Failed opening required '../app/models/registrasi_model.php' (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\muspusdirla\application\controllers\datakoleksi.php


    bang mau tnya, ini kenapa yah modelny gk kebaca?? pdhala udh tak samain kek d yt sma d sni. baseurlnya udh tak cek sma. Tapi tetap aja kyak ini

    ReplyDelete
  6. mas, yang updatenya itu cuma ngebaca doang ya di edit.php, gabisa diupdate??

    ReplyDelete
  7. Waktu di hosting kok ngga bisa mas,.. apa harus ada yang diubah lagi?

    ReplyDelete
  8. Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '='1'' at line 1 in C:\xampp\htdocs\phpmvc\app\core\Database.php:51 Stack trace: #0 C:\xampp\htdocs\phpmvc\app\core\Database.php(51): PDOStatement->execute() #1 C:\xampp\htdocs\phpmvc\app\core\Database.php(60): Database->execute() #2 C:\xampp\htdocs\phpmvc\app\models\Mahasiswa_model.php(18): Database->single() #3 C:\xampp\htdocs\phpmvc\app\controllers\Mahasiswa.php(13): Mahasiswa_model->getMahasiswaById('1') #4 C:\xampp\htdocs\phpmvc\app\core\App.php(36): Mahasiswa->detail('1') #5 C:\xampp\htdocs\phpmvc\public\index.php(5): App->__construct() #6 {main} thrown in C:\xampp\htdocs\phpmvc\app\core\Database.php on line 51


    bang salahnya dimana ya? saya sudah ikutin semua sintaksnya dengan benar tp muncul pesan PDO Exceptionnya tidak ketangkep. gimana ya bang
    kira-kira?

    ReplyDelete
  9. halo, ko di index paling utama error keluarnya begini ya?


    Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\belajar_mvc\app\core\App.php on line 19

    mohon pencerahannya

    ReplyDelete

Post a Comment

Popular posts from this blog

IT Asset Management Dengan PHP MySQL

Laravel - Sistem Informasi Perpustakaan Sederhana Laravel