query($query); if ($result->num_rows > 0) { // Extract existing code $row = $result->fetch_assoc(); $lastCode = $row['kode_barang']; // Extract the numeric part and increment $numericPart = intval(substr($lastCode, 3)); // Extract numbers after 'BRG' $nextNumeric = $numericPart + 1; // Format with leading zeros (e.g., BRG001, BRG002, etc.) $newCode = 'BRG' . str_pad($nextNumeric, 3, '0', STR_PAD_LEFT); } else { // If no existing codes, start with BRG001 $newCode = 'BRG001'; } return $newCode; } if ($_SERVER["REQUEST_METHOD"] == "POST") { // Generate new product code $kode_barang = generateProductCode($conn); // Get data from form $nama_barang = isset($_POST['nama_barang']) ? $_POST['nama_barang'] : ''; $id_jenis = isset($_POST['id_jenis']) ? $_POST['id_jenis'] : ''; $stok = isset($_POST['stok']) ? $_POST['stok'] : 0; $harga = isset($_POST['harga']) ? $_POST['harga'] : ''; // Check if image file was uploaded if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) { $image = $_FILES['image']; // Validate image $image_name = basename($image['name']); $target_dir = "image/"; // Target folder to store images $target_file = $target_dir . $image_name; $image_file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION)); // Check if uploaded file is an image if (in_array($image_file_type, ['jpg', 'jpeg', 'png', 'gif'])) { // Move file to target folder if (!move_uploaded_file($image['tmp_name'], $target_file)) { echo "Error: Failed to upload image!"; exit; } } else { echo "Error: Only images (JPG, JPEG, PNG, GIF) are allowed!"; exit; } } else { $image_name = ''; // If no image was uploaded, set image name to empty } // Validate id_jenis $query_jenis = "SELECT id_jenis FROM jenis_barang WHERE id_jenis = ?"; $stmt_jenis = $conn->prepare($query_jenis); $stmt_jenis->bind_param("i", $id_jenis); $stmt_jenis->execute(); $stmt_jenis->store_result(); if ($stmt_jenis->num_rows == 0 && $id_jenis != '') { echo "Error: Category not found!"; exit; } // Validate stock and price must be numbers if (!preg_match('/^\d+$/', $stok) || !preg_match('/^\d+$/', $harga)) { die(""); } // Convert to integers for safety $stok = intval($stok); $harga = intval($harga); // Insert data into database (now including kode_barang) $sql = "INSERT INTO barang (kode_barang, nama_barang, id_jenis, stok, harga, image) VALUES (?, ?, ?, ?, ?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param("ssisis", $kode_barang, $nama_barang, $id_jenis, $stok, $harga, $image_name); if ($stmt->execute()) { echo ""; } else { echo "Error: " . $stmt->error; } $stmt->close(); } // Fetch categories for the dropdown $query_categories = "SELECT id_jenis, nama_jenis FROM jenis_barang ORDER BY nama_jenis"; $result_categories = $conn->query($query_categories); ?> Dreams Pos admin template
img

Drag and drop a file to upload

Cancel