Home Database OOP : CRUD With PHP Native

OOP : CRUD With PHP Native

0

Apa itu OOP?

OOP (Object-Oriented Programming) atau Pemrograman Berorientasi Objek adalah paradigma pemrograman yang digunakan dalam PHP, yang memungkinkan Anda untuk mengorganisasi kode Anda ke dalam objek-objek yang memiliki properti (variabel) dan metode (fungsi). Dalam PHP, Anda dapat membuat kelas, yang merupakan blueprint atau cetakan untuk objek, dan kemudian membuat objek berdasarkan kelas tersebut.

Langkah – Langkah Membuat CRUD

  • Membuat Koneksi dengan database
<?php
 
class Database
{
    private $host = "localhost";
    private $user = "root";
    private $pass = "";
    private $name = "contoh_crud";
    private $conn;
 
    public function __construct()
    {
        $this->conn = new mysqli($this->host, $this->user, $this->pass, $this->name);
 
        if ($this->conn->connect_error) {
            die("Koneksi Dengan Database Gagal: " . $this->conn->connect_error);
        }
    }
 
    public function getConnection()
    {
        return $this->conn;
    }
}
 
$database = new Database();
$link = $database->getConnection();
 
if (!$link) {
    die("Koneksi Dengan Database Gagal: " . mysqli_connect_errno() . " - " . mysqli_connect_error());
}
  • Setelah Membuat Koneksi langsung saja membuat tampilan nya 
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contoh Crud</title>
</head>
 
<body>
    <h1>Data Produk</h1>
    <a href="create.php">Tambahkan Data</a>
    <table border='1'>
        <tr>
            <th>No</th>
            <th>Nama</th>
            <th>Harga</th>
            <th>Jumlah</th>
            <th>Aksi</th>
        </tr>
        <?php
        require_once 'koneksi.php';
 
        $db = new Database();
        $conn = $db->getConnection();
        $query = "SELECT * FROM produk";
        $result = $conn->query($query);
 
        if ($result->num_rows > 0) {
            $no = 1;
            while ($row = $result->fetch_assoc()) {
                echo "<tr>";
                echo "<td>" . $no . "</td>";
                echo "<td>" . $row['nama'] . "</td>";
                echo "<td>" . $row['harga'] . "</td>";
                echo "<td>" . $row['jumlah'] . "</td>";
                echo "<td><a href='edit.php?id=" . $row['id'] . "'>Edit</a> | <a href='delete.php?id=" . $row['id'] . "'>Delete</a></td>";
                echo "</tr>";
                $no++;
            }
        }
        ?>
    </table>
</body>
 
</html> 
  • Membuat Form & Controller Untuk Menambahkan Data
    Create.php
<?php
require_once 'koneksi.php';
require_once 'create_proses.php';
 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $nama = $_POST['nama'];
    $harga = $_POST['harga'];
    $jumlah = $_POST['jumlah'];
 
    $database = new Database();
    $db = $database->getConnection();
 
    $produk = new Produk($db);
 
    if ($produk->createProduct($nama, $harga, $jumlah)) {
        header("Location: index.php");
        exit;
    } else {
        echo "Gagal menambahkan data.";
    }
}
 
?>
 
<!DOCTYPE html>
<html>
 
<head>
    <title>Tambah Produk Baru</title>
</head>
 
<body>
    <h2>Tambah Produk Baru</h2>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <label for="nama">Nama:</label>
        <input type="text" name="nama" required><br>
 
        <label for="harga">Harga:</label>
        <input type="text" name="harga" required><br>
 
        <label for="jumlah">Jumlah:</label>
        <input type="text" name="jumlah" required><br>
 
        <input type="submit" value="Simpan">
    </form>
    <br>
    <a href="index.php">Kembali ke Daftar Produk</a>
</body>
 
</html>

Create_proses.php

<?php
class Produk
{
    private $conn;
    private $table = 'produk';
 
    public function __construct($db)
    {
        $this->conn = $db;
    }
 
    public function createProduct($nama, $harga, $jumlah)
    {
        $query = "INSERT INTO " . $this->table . " (nama, harga, jumlah) VALUES (?, ?, ?)";
        $stmt = $this->conn->prepare($query);
 
        $nama = htmlspecialchars(strip_tags($nama));
        $harga = htmlspecialchars(strip_tags($harga));
        $jumlah = htmlspecialchars(strip_tags($jumlah));
 
        $stmt->bind_param("sss", $nama, $harga, $jumlah);
 
        if ($stmt->execute()) {
            return true;
        } else {
            return false;
        }
    }
}
  • Selanjutnya kita membuat Form Edit & Controllernya
    Edit.php
<?php
require_once 'koneksi.php';
 
class Produk
{
    private $conn;
 
    public function __construct($db)
    {
        $this->conn = $db;
    }
 
    public function getProductById($id)
    {
        $query = "SELECT nama, harga, jumlah FROM produk WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
 
        if ($result->num_rows > 0) {
            return $result->fetch_assoc();
        } else {
            return null;
        }
    }
}
 
if (isset($_GET['id'])) {
    $id = $_GET['id'];
 
    $database = new Database();
    $db = $database->getConnection();
 
    $produk = new Produk($db);
    $productData = $produk->getProductById($id);
 
    if ($productData) {
        $nama = $productData['nama'];
        $harga = $productData['harga'];
        $jumlah = $productData['jumlah'];
    } else {
        echo "Data tidak ditemukan.";
        exit;
    }
} else {
    echo "ID Produk tidak ditemukan.";
}
?>
 
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Produk</title>
</head>
 
<body>
    <h2>Edit Produk</h2>
    <form method="post" action="edit_proses.php">
        <input type="hidden" name="id" value="<?php echo $id; ?>">
 
        <label for="nama">Nama:</label>
        <input type="text" name="nama" value="<?php echo $nama; ?>" required><br>
 
        <label for="harga">Harga:</label>
        <input type="text" name="harga" value="<?php echo $harga; ?>" required><br>
 
        <label for="jumlah">Jumlah:</label>
        <input type="text" name="jumlah" value="<?php echo $jumlah; ?>" required><br>
 
        <input type="submit" value="Simpan Perubahan">
    </form>
    <br>
    <a href="index.php">Kembali ke Daftar Produk</a>
</body>
 
</html>

edit_proses.php

<?php
require_once 'koneksi.php';
 
class Produk
{
    private $conn;
 
    public function __construct($db)
    {
        $this->conn = $db;
    }
 
    public function updateProduct($id, $nama, $harga, $jumlah)
    {
        $query = "UPDATE produk SET nama = ?, harga = ?, jumlah = ? WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("sssi", $nama, $harga, $jumlah, $id);
 
        if ($stmt->execute()) {
            return true;
        } else {
            return false;
        }
    }
}
 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $id = $_POST['id'];
    $nama = $_POST['nama'];
    $harga = $_POST['harga'];
    $jumlah = $_POST['jumlah'];
 
    $database = new Database();
    $db = $database->getConnection();
 
    $produk = new Produk($db);
 
    if ($produk->updateProduct($id, $nama, $harga, $jumlah)) {
        header("Location: index.php");
        exit;
    } else {
        echo "Gagal memperbarui data.";
    }
}
  • Dan yang terakhir kita akan membuat fitur delete
    Delete.php
<?php
require_once 'koneksi.php';
 
class Produk
{
    private $conn;
 
    public function __construct($db)
    {
        $this->conn = $db;
    }
 
    public function deleteProduct($id)
    {
        $query = "DELETE FROM produk WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("i", $id);
 
        if ($stmt->execute()) {
            return true;
        } else {
            return false;
        }
    }
}
 
if (isset($_GET['id'])) {
    $id = $_GET['id'];
 
    $database = new Database();
    $db = $database->getConnection();
 
    $produk = new Produk($db);
 
    if ($produk->deleteProduct($id)) {
        header("Location: index.php");
        exit;
    } else {
        echo "Gagal menghapus produk.";
        exit;
    }
} else {
    echo "ID Produk tidak ditemukan.";
}