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());
}
}
}
?>
*****
Ini batas akhir script untuk file Database.php
*****
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);
}
}
?>
*****
Ini batas akhir untuk file Item.php
*****
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>
*****
Ini batas akhir untuk file index.php
****
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
);
****
Sampai di sini, kita sudah punya file Database.php, Item.php, dan index.php, serta database "oop_db" yang memuat tabel "items".
***
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.
|
"Boleh Konsultasi Masuk Jurusan Sistem Informasi via Tiktok: @katabahcom."
|
|
Tips Skripsi Program Studi Sistem Informasi |
|
|
No comments:
Post a Comment