Lompat ke konten Lompat ke sidebar Lompat ke footer

Cara Membuat CRUD PHP MySQL dengan Mudah

buatlah database dengan nama db_product kemudian buatlah sebuah tabel dengan menjalankan script berikut :

Langkah#1

CREATE TABLE `products` (  `id` int(11) NOT NULL,  `title` varchar(200) NOT NULL,  `price` float NOT NULL,  `company` varchar(200) NOT NULL,  `category` varchar(200) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Langkah#2

Tambahkan beberapa data dengan menjalankan script berikut ini :

INSERT INTO `products` (`id`, `title`, `price`, `company`, `category`) VALUES(1, 'Buku', 300000, 'Company 1', 'Pakaian'),(2, 'Buku Tulis', 500000, 'Company 1', 'Pakaian'),(3, 'Pena', 4000, 'Joyko', 'ATK'),(6, 'Kopi', 5000, 'Torabika', 'Minuman');

Langkah#3

Buka command prompt (cmd) kemudian jalankan perintah berikut :

Create Project dan Instal Library thingengineer/mysqli-database-class:dev-master

Penjelasan :

  • Langkah pertama adalah membuka cmd
  • perintah cd\ berguna untuk masuk ke drive c:
  • perintah cd\xampp\htdocs\ untuk masuk ke folder htdocs dimana lokasi folder kita agar dapat diakses oleh server.
  • perintah mkdir pos berguna untuk membuat folder pos dalam hal ini pos adalah nama project yang akan kita buat.
  • jalankan perintah : composer require thingengineer/mysqli-database-class:dev-master perintah diatas adalah library mysqli yang akan memudahkan kita dalam membuat aplikasi.
  • perintag code . digunakan untuk membuka project dengan visual studio code.

Langkah#4

Setelah project terbuka pada visual studio code kita perlu menambahkan beberapa file agar kita siap untuk bekerja. struktur folder yang ada pada project seperti pada gambar berikut :

Struktur Folder Project

buatlah folder dan file-file seperti pada gambar diatas, selanjutnya kita akan membuat coding pada file-file tersebut :

Coding error.php

<!DOCTYPE html><html lang="en"><?php$title = "Not Found";$judul = $halaman;?><head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Halaman Error</title></head><body>    <p>Maaf, Halaman <strong>"<?= $halaman ?>"</strong> Tidak Ditemukan</p>;</body></html>

coding product.php

<?php$title = "Product List";$judul = $title;$url = 'products';?><?phpif (isset($_POST['simpan'])) {    if ($_POST['id'] == "") {        $data['title'] = $_POST['title'];        $data['price'] = $_POST['price'];        $data['company'] = $_POST['company'];        $data['category'] = $_POST['category'];        $exec = $db->insert("products", $data);    } else {        $data['title'] = $_POST['title'];        $data['price'] = $_POST['price'];        $data['company'] = $_POST['company'];        $data['category'] = $_POST['category'];        $db->where('id', $_POST['id']);        $exec = $db->update("products", $data);    }    redirect(url($url));}?><?phpif (isset($_GET['hapus'])) {    $db->where('id', $_GET['id']);    $get = $db->ObjectBuilder()->getOne('products');    $db->where("id", $_GET['id']);    $exec = $db->delete("products");    redirect(url($url));} elseif (isset($_GET['tambah']) or isset($_GET['ubah'])) {    $id = "";    $title = "";    $price = "";    $company = "";    $category = "";    if (isset($_GET['ubah']) and isset($_GET['id'])) {        $id = $_GET['id'];        $db->where('id', $id);        $row = $db->ObjectBuilder()->getOne('products');        if ($db->count > 0) {            $id = $row->id;            $title = $row->title;            $price = $row->price;            $company = $row->company;            $category = $row->category;        }    }    ?>    <form method="post">        <input type="hidden" id="id" name="id" value="<?=$id?>">        <div class="form-group">            <label>Kode</label>            <div class="row">                <div class="col-md-4">                    <input type="text" id="id" name="id" value="<?=$id?>">                </div>            </div>        </div>        <div class="form-group">            <label>Title</label>            <div class="row">                <div class="col-md-6">                    <input type="text" id="title" name="title" value="<?=$title?>">                </div>            </div>        </div>        <div class="form-group">            <label>Price</label>            <div class="row">                <div class="col-md-6">                    <input type="text" id="price" name="price" value="<?=$price?>">                </div>            </div>        </div>        <div class="form-group">            <label>Company</label>            <div class="row">                <div class="col-md-4">                    <input type="text" id="company" name="company" value="<?=$company?>">                </div>            </div>        </div>        <div class="form-group">            <label>Kategori</label>            <div class="row">                <div class="col-md-3">                    <input type="text" id="category" name="category" value="<?=$category?>">                </div>            </div>        </div>        <div class="form-group">            <button type="submit" name="simpan" class="btn btn-info"><i class="fa fa-save"></i> Simpan</button>            <a href="<?=url($url)?>" class="btn btn-danger"><i class="fa fa-reply"></i> Kembali</a>        </div>    </form><?php } else {?>    <a href="<?=url($url . '&tambah')?>" class="btn btn-success"><i class="fa fa-plus"></i> Tambah</a>    <table class="table table-bordered">        <thead>            <tr>                <th>No</th>                <th>Title</th>                <th>Price</th>                <th>Company</th>                <th>Category</th>                <th>Aksi</th>            </tr>        </thead>        <tbody>            <?php$no = 1;    $getdata = $db->ObjectBuilder()->get('products');    foreach ($getdata as $row) {        ?>                <tr>                    <td><?=$no?></td>                    <td><?=$row->title?></td>                    <td><?=$row->price?></td>                    <td><?=$row->company?></td>                    <td><?=$row->category?></td>                    <td>                        <a href="<?=url($url . '&ubah&id=' . $row->id)?>"> Edit</a>                        <a href="<?=url($url . '&hapus&id=' . $row->id)?>" onclick="return confirm('Hapus data?')">Hapus</a>                    </td>                </tr>        <?php$no++;    }}?>        </tbody>    </table>

coding crud_db.php

<?php$db = new MysqliDb($setDb['db_host'], $setDb['db_user'], $setDb['db_password'], $setDb['db_name']);

coding helper.php

<?phpfunction base_url($a = ''){    $getbase_url = $GLOBALS['setUri']['base'];    return $getbase_url . $a;}function assets($a = ''){    $getbase_assets = $GLOBALS['setUri']['assets'];    return base_url($getbase_assets . $a);}function url($a = '', $b = ''){    return base_url($b . '?halaman=' . $a);}function redirect($a = ''){    header("location: " . $a);    exit;}function templates($a = ''){    return assets($GLOBALS['template'] . $a);}

coding session.php

<?phpuse Josantonius\Session\Session;$session = new Session();if ($session::init()) {    $session::init();}$session::setPrefix('_Webgis');

coding head.php

<head>  <meta charset="utf-8">  <meta http-equiv="X-UA-Compatible" content="IE=edge">  <title><?= isset($title) ? $title : 'CRUD Products' ?></title>  <!-- Tell the browser to be responsive to screen width -->  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"></head>

coding loader.php

<?php$_dir = __DIR__;define('env', $_dir);include env . '/env.php';// helpersinclude 'vendor/autoload.php';include '_helpers/helper.php';include '_helpers/crud_db.php';//include '_helpers/session.php';

coding env.php

<?php$_dir = __DIR__;define('env', $_dir);include env . '/env.php';// helpersinclude 'vendor/autoload.php';include '_helpers/helper.php';include '_helpers/crud_db.php';//include '_helpers/session.php';

coding index.php

<?phpinclude '_loader.php';if (isset($_GET['halaman'])) {    $halaman = $_GET['halaman'];} else {    $halaman = 'beranda';}ob_start();$file = '_halaman/' . $halaman . '.php';if (!file_exists($file)) {    include '_halaman/error.php';} else {    include $file;}$content = ob_get_contents();ob_end_clean();?><!DOCTYPE html><html lang="en"><?phpinclude '_layouts/head.php'?><body>    <div>        <div>            <h1> <?php echo $judul ?> </h1>            <?php echo $content;  ?>        </div>    </div></body></html>

Langkah#5

jika sudah selesai membuat coding diatas silahkan jalankan program anda dengan mengakses url seperti berikut :

http://localhost/pos/?halaman=products

maka hasilnya :

Halaman Produk

Posting Komentar untuk "Cara Membuat CRUD PHP MySQL dengan Mudah"