beginTransaction();
// Insert test
$stmt = $pdo->prepare("INSERT INTO tests (user_id, title, description, is_public) VALUES (?, ?, ?, ?)");
$stmt->execute([$user_id, $title, $description, $is_public]);
$test_id = $pdo->lastInsertId();
// Insert questions and options
foreach ($questions as $q_data) {
$question_text = trim($q_data['text'] ?? '');
if (empty($question_text)) continue;
$stmt = $pdo->prepare("INSERT INTO questions (test_id, question_text) VALUES (?, ?)");
$stmt->execute([$test_id, $question_text]);
$question_id = $pdo->lastInsertId();
$options = $q_data['options'] ?? [];
$correct_option_index = isset($q_data['correct']) ? intval($q_data['correct']) : -1;
foreach ($options as $index => $option_text) {
$option_text = trim($option_text);
if(empty($option_text)) continue;
$is_correct = ($index === $correct_option_index);
$stmt = $pdo->prepare("INSERT INTO options (question_id, option_text, is_correct) VALUES (?, ?, ?)");
$stmt->execute([$question_id, $option_text, $is_correct]);
}
}
$pdo->commit();
$message = "Test created successfully!";
} catch (PDOException $e) {
$pdo->rollBack();
$error = "Database error: " . $e->getMessage();
}
} else {
$error = "Could not connect to the database.";
}
}
}
?>