Pages

Prodi Sistem Informasi | Belajar HTML dan PHP | Skripsi SI
1000 Penghafal Quran
Pengobatan Ruqyah Mandiri
Sistem Informasi (S1)
Manajemen Informatika
Komputer dan Pendidikan
Blog | Kontak | Siap Kerja | Sertifikat | PrivacyPolicy | Inggris Arab | Daftar Isi

Tuesday, February 4, 2025

OOP

Materi awal dari web W3Schools. Selanjutnya, membuat CRUD yang melibatkan database dengan minimal penguasaan tombol tambah dan tampilan.

https://parsinta.com/articles/pemrograman-berorientasi-objek-di-php-hzcxd


http://rizkimuliono.blog.uma.ac.id/2020/01/27/pemrograman-web-ii-php-object-oriented-programming-oop/#


https://www.akscoding.com/2022/02/bject-oriented-programming-oop-pada-php.html

Dds

 

Pertemuan 8:

https://www.malasngoding.com/php-oop-part-2-pengertian-class-object-property-dan-method/

**

TOMBOL TAMBAH 

Struktur Folder 

- index.php

- classes/

   - Database.php

   - Item.php

**

classes/Database.php

<?php

class Database {

    private $host = 'localhost';

    private $dbname = 'oop_db';

    private $username = 'root';

    private $password = '';

    public $conn;


    public function __construct() {

        try {

            $this->conn = new PDO("mysql:host={$this->host};dbname={$this->dbname}", 

                                  $this->username, $this->password);

            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        } catch (PDOException $e) {

            die("Koneksi gagal: " . $e->getMessage());

     

   }

    }

}

?>


**

classes/Item.php

<?php

require_once 'Database.php';


class Item {

    private $db;


    public function __construct() {

        $database = new Database();

        $this->db = $database->conn;

    }


    public function addItem($name) {

        $stmt = $this->db->prepare("INSERT INTO items (name) VALUES (:name)");

        $stmt->bindParam(':name', $name);

        return $stmt->execute();

    }


    public function getItems() {

        $stmt = $this->db->query("SELECT * FROM items ORDER BY id DESC");

        return $stmt->fetchAll(PDO::FETCH

_ASSOC);

    }

}

?>

**

index.php

<?php

require_once 'classes/Item.php';


$itemObj = new Item();


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['name'])) {

    $itemObj->addItem($_POST['name']);

}


$items = $itemObj->getItems();

?>


<!DOCTYPE html>

<html>

<head>

    <title>Tambah Item (OOP + DB)</title>

</head>

<body>

    <h1>Tambah Item</h1>

    <form method="post">

        <input type="text" name="name" placeholder="Nama item" required>

        <button type="submit">Tambah</button>

    </form>


    <h2>Daftar Item</h2>

    <ul>

        <?php foreach ($items as $item): ?>

            <li><?= htmlspecialchars($item['name']) ?></li>

        <?php endforeach; 

?>

    </ul>

</body>

</html>

**

Struktur Tabel MySQL 

CREATE DATABASE IF NOT EXISTS oop_db;

USE oop_db;


CREATE TABLE IF NOT EXISTS items (

    id INT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(100) NOT NU

LL

);

**

Penjelasan OOP:

Kelas Database mengelola koneksi database (reusable).

Kelas Item mengelola logika bisnis (insert dan ambil data).

index.php hanya sebagai tampilan dan handler form, menjaga prinsip separation of concerns dalam OOP.


**

**

EDIT DAN HAPUS OOP

Struktur Folder

- index.php (Halaman utama - Read & Create)

- edit.php (Halaman Edit)

- delete.php (Halaman Delete)

- classes/

   - Database.php

   - Item.php

**

classes/Database.php

<?php

class Database {

    private $host = 'localhost';

    private $dbname = 'oop_db';

    private $username = 'root';

    private $password = '';

    public $conn;


    public function __construct() {

        try {

            $this->conn = new PDO("mysql:host={$this->host};dbname={$this->dbname}", 

                                  $this->username, $this->password);

            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        } catch (PDOException $e) {

            die("Koneksi gagal: " . $e->getMessage());

     

   }

    }

}

?>


**

classes/Item.php

<?php

require_once 'Database.php';


class Item {

    private $db;


    public function __construct() {

        $database = new Database();

        $this->db = $database->conn;

    }


    public function addItem($name) {

        $stmt = $this->db->prepare("INSERT INTO items (name) VALUES (:name)");

        $stmt->bindParam(':name', $name);

        return $stmt->execute();

    }


    public function getItems() {

        $stmt = $this->db->query("SELECT * FROM items ORDER BY id DESC");

        return $stmt->fetchAll(PDO::FETCH_ASSOC);

    }


    public function getItem($id) {

        $stmt = $this->db->prepare("SELECT * FROM items WHERE id = :id");

        $stmt->bindParam(':id', $id);

        $stmt->execute();

        return $stmt->fetch(PDO::FETCH_ASSOC);

    }


    public function updateItem($id, $name) {

        $stmt = $this->db->prepare("UPDATE items SET name = :name WHERE id = :id");

        $stmt->bindParam(':name', $name);

        $stmt->bindParam(':id', $id);

        return $stmt->execute();

    }


    public function deleteItem($id) {

        $stmt = $this->db->prepare("DELETE FROM items WHERE id = :id");

        $stmt->bindParam(':id', $id);

    

    return $stmt->execute();

    }

}

?>

**

index.php

<?php

require_once 'classes/Item.php';


$itemObj = new Item();


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['name'])) {

    $itemObj->addItem($_POST['name']);

    header("Location: index.php");

    exit();

}


$items = $itemObj->getItems();

?>


<!DOCTYPE html>

<html>

<head><title>CRUD PHP OOP</title></head>

<body>

    <h1>Tambah Item</h1>

    <form method="post">

        <input type="text" name="name" required placeholder="Nama item">

        <button type="submit">Tambah</button>

    </form>


    <h2>Daftar Item</h2>

    <ul>

        <?php foreach ($items as $item): ?>

            <li>

                <?= htmlspecialchars($item['name']) ?>

                [<a href="edit.php?id=<?= $item['id'] ?>">Edit</a>] 

                [<a href="delete.php?id=<?= $item['id'] ?>" onclick="return confirm('Yakin hapus?')">Hapus</a>]

            </li>

        <?php endforea

ch; ?>

    </ul>

</body>

</html>

**

edit.php

<?php

require_once 'classes/Item.php';

$itemObj = new Item();


$id = $_GET['id'] ?? null;

$item = $itemObj->getItem($id);


if (!$item) {

    echo "Data tidak ditemukan!";

    exit();

}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['name'])) {

    $itemObj->updateItem($id, $_POST['name']);

    header("Location: index.php");

    exit();

}

?>


<!DOCTYPE html>

<html>

<head><title>Edit Item</title></head>

<body>

    <h1>Edit Item</h1>

    <form method="post">

        <input type="text" name="name" value="<?= htmlspecialchars($item['name']) ?>" required>

        <button type="submit">Simpan</button>

    </form>

    <a href="index.php"

>Kembali</a>

</body>

</html>


**

delete.php

<?php

require_once 'classes/Item.php';

$itemObj = new Item();


$id = $_GET['id'] ?? null;


if ($id) {

    $itemObj->deleteItem($id);

}


header("Location: index.php"

);

exit();

**

Struktur Tabel MySQL 

CREATE DATABASE IF NOT EXISTS oop_db;

USE oop_db;


CREATE TABLE IF NOT EXISTS items (

    id INT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(100) NOT NULL

);



**

Penjelasan Konsep OOP:

Class Item berisi logika bisnis.

Class Database bertanggung jawab untuk koneksi.

index.php, edit.php, delete.php adalah bagian frontend / view.

OOP digunakan untuk memisahkan logika data dari tampilan antarmuka.


No comments:

Post a Comment

Tips Mendidik Anak Balita TikTok @ois.tok

Tips Skripsi Program Studi Sistem Informasi

Peluang Magang Jurusan SI

Kupas Tuntas Jurusan Sistem Informasi

Technopreneur: Pengusaha IT Sebelum Lulus

Pekerjaan Data Analyst dan Data Science

Ruang Digital

Jurusan SI Minimal Kuasai 4 Mata Kuliah Ini!

Contoh Visualisasi Data Untuk Skripsi SI

Kuliah Sistem Informasi | Mata Kuliah | Prestasi | Partners | Kelompok Keahlian | Peluang Kerja SI | Ruang Digital | Parenting: Calistung, Hapalan Quran, Keluarga