pyolingo/forms/hinzuefuegenKarte.php
2026-04-07 17:25:06 +02:00

90 lines
3.3 KiB
PHP

<?php
require_once __DIR__ . '/../includes/db_connect.php';
session_start();
$_SESSION['old'] = $_POST;
$return = $_POST['return'] ?? 'allgemein';
$kategorie = $_POST['kategorie'] ?? 'substantive';
$deutsch = trim($_POST['deutsch'] ?? '');
for($i = 0; $i < 7; $i++) {
$italienisch[$i] = trim($_POST['italienisch_' . $i] ?? '');
$farbe[$i] = $_POST['farbe_' . $i] ?? 'black';
}
if($deutsch === '') {
$_SESSION['error'] = "Das deutsche Wort darf nicht leer sein!";
header("Location: ../$return.php");
exit;
}
if($italienisch[0] === '') {
$_SESSION['error'] = "Das erste italienische Wort darf nicht leer sein!";
header("Location: ../$return.php");
exit;
}
insertDB($pdo, $kategorie, $deutsch, $italienisch, $farbe);
unset($_SESSION['old']);
function insertDB(PDO $pdo, string $kategorie, string $deutsch, array $italienisch, array $farbe) {
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare("SELECT id
FROM deutsch
WHERE LOWER(wort) = LOWER(:deutsch);");
$stmt->execute(['deutsch' => $deutsch]);
if($stmt->fetchColumn() != null) throw new Exception('deutsches Wort bereits vorhanden');
$stmt = $pdo->prepare("SELECT id
FROM kategorie
WHERE LOWER(name) = LOWER(:kategorie);");
$stmt->execute(['kategorie' => $kategorie]);
$kategorie_id = $stmt->fetchColumn();
$stmt = $pdo->query("SELECT id,
farbe
FROM farbe;");
$farbe_array = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $pdo->prepare("INSERT INTO deutsch(wort, kategorie_id, wort_hinzugefuegt)
VALUES (:wort, :kategorie_id, (:wort_hinzugefuegt)::timestamp);");
$stmt->execute(['wort' => $deutsch,
'kategorie_id' => $kategorie_id,
'wort_hinzugefuegt' => date('Y-m-d H:i:s')]);
$stmt = $pdo->prepare("SELECT id
FROM deutsch
WHERE LOWER(wort) = LOWER(:deutsch);");
$stmt->execute(['deutsch' => $deutsch]);
$deutsch_id = $stmt->fetchColumn();
for($i = 0; $i < 7; $i++) {
$farbe_id = -1;
foreach($farbe_array as $it_farbe) if($it_farbe['farbe'] == $farbe[$i]) $farbe_id = $it_farbe['id'];
$stmt = $pdo->prepare("INSERT INTO italienisch (wort, deutsch_id, farbe_id)
VALUES (:italienisch, :deutsch_id, :farbe_id)");
$stmt->execute(['italienisch' => $italienisch[$i],
'deutsch_id' => $deutsch_id,
'farbe_id' => $farbe_id]);
}
$pdo->commit();
return 0;
} catch(Exception $e) {
$pdo->rollBack();
echo "Fehler: " . $e->getMessage();
return 1;
}
}
$_SESSION['success'] = "neues Wort gespeichert";
header("Location: ../$return.php");
exit;
?>