prepare("SELECT id FROM `$table` WHERE `$name_column` = ?"); $stmt->execute([$name_value]); $id = $stmt->fetchColumn(); if (!$id) { $cols = '`' . $name_column . '`'; $vals = '?'; $exec_vals = [$name_value]; foreach ($extra_cols as $col => $val) { $cols .= ', '`' . $col . '`'; $vals .= ', ?'; $exec_vals[] = $val; } $stmt = $pdo->prepare("INSERT INTO `$table` ($cols) VALUES ($vals)"); $stmt->execute($exec_vals); $id = $pdo->lastInsertId(); } return $id; } if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES['csv_file'])) { $file = $_FILES['csv_file']['tmp_name']; if (($handle = fopen($file, "r")) !== FALSE) { $pdo = db(); $pdo->beginTransaction(); try { // Skip header row fgetcsv($handle, 1000, ","); $imported_count = 0; $sql = "INSERT INTO expenses (expense_date, title, amount, currency, expense_type, category_id, user_id, account_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; $stmt = $pdo->prepare($sql); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { // CSV format: Date,Title,Category,Account,User,Type,Amount,Currency $date = $data[0]; $title = $data[1]; $category_name = $data[2]; $account_name = $data[3]; $user_name = $data[4]; $expense_type = $data[5]; $amount = $data[6]; $currency = $data[7]; $category_id = find_or_create($pdo, 'categories', 'name', $category_name); $user_id = find_or_create($pdo, 'users', 'name', $user_name, ['email' => strtolower(str_replace(' ', '.', $user_name)).'@example.com']); $account_id = find_or_create($pdo, 'accounts', 'name', $account_name, ['user_id' => $user_id, 'currency' => $currency]); $stmt->execute([$date, $title, $amount, $currency, $expense_type, $category_id, $user_id, $account_id]); $imported_count++; } $pdo->commit(); $message = "Successfully imported $imported_count expenses!"; } catch (Exception $e) { $pdo->rollBack(); $error = "Import failed: " . $e->getMessage(); } fclose($handle); } else { $error = "Could not open the uploaded file."; } } ?>