Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- require 'db.php';
- // Ambil kategori untuk dropdown
- $query = "SELECT * FROM categories";
- $categories = mysqli_query($conn, $query);
- if ($_SERVER['REQUEST_METHOD'] === 'POST') {
- // Validasi input
- $name = trim($_POST['name']);
- $category_id = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
- $quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 0;
- $price = isset($_POST['price']) ? (float)$_POST['price'] : 0.0;
- // Pastikan input tidak kosong
- if (empty($name)) {
- echo "Nama barang tidak boleh kosong.";
- exit;
- }
- if ($quantity <= 0) {
- echo "Jumlah harus lebih besar dari 0.";
- exit;
- }
- if ($price <= 0) {
- echo "Harga harus lebih besar dari 0.";
- exit;
- }
- // Siapkan query dengan prepared statements
- $query = "INSERT INTO items (name, category_id, quantity, price) VALUES (?, ?, ?, ?)";
- $stmt = mysqli_prepare($conn, $query);
- // Bind parameter
- mysqli_stmt_bind_param($stmt, "siid", $name, $category_id, $quantity, $price);
- // Eksekusi query
- if (mysqli_stmt_execute($stmt)) {
- header('Location: index.php');
- exit;
- } else {
- echo 'Gagal menambahkan barang: ' . mysqli_error($conn);
- }
- // Tutup statement
- mysqli_stmt_close($stmt);
- }
- // Tutup koneksi
- mysqli_close($conn);
- ?>
- <!DOCTYPE html>
- <html lang="id">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Tambah Barang</title>
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
- </head>
- <body>
- <div class="container mt-4">
- <h1 class="mb-4">Tambah Barang</h1>
- <form method="post">
- <div class="form-group">
- <label for="name">Nama Barang:</label>
- <input type="text" class="form-control" id="name" name="name" required>
- </div>
- <div class="form-group">
- <label for="category_id">Kategori:</label>
- <select class="form-control" id="category_id" name="category_id">
- <option value="">Pilih Kategori</option>
- <?php while ($row = mysqli_fetch_assoc($categories)): ?>
- <option value="<?= htmlspecialchars($row['id']) ?>">
- <?= htmlspecialchars($row['name']) ?>
- </option>
- <?php endwhile; ?>
- </select>
- </div>
- <div class="form-group">
- <label for="quantity">Jumlah:</label>
- <input type="number" class="form-control" id="quantity" name="quantity" min="1" required>
- </div>
- <div class="form-group">
- <label for="price">Harga:</label>
- <input type="number" class="form-control" id="price" name="price" step="0.01" min="0.01" required>
- </div>
- <button type="submit" class="btn btn-primary">Simpan</button>
- </form>
- </div>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement