<?php
session_start();
// Check if user is logged in
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
header("Location: login.php");
exit();
}
// Connect to the database
$LINK = mysqli_connect('127.0.0.1', 'tyrfl709', '[q8OXd*BEbxW6bM4', 'tyrfl709');
if (!$LINK) {
die("Database connection error: " . mysqli_connect_error());
}
// Optional: display errors during development
ini_set('display_errors', '1');
error_reporting(E_ALL);
// If the Save button was clicked, update the selected page content
if (isset($_POST['BUTTON_save'])) {
$pageToSave = mysqli_real_escape_string($LINK, $_POST['DATA_page']);
$newContent = mysqli_real_escape_string($LINK, $_POST['DATA_content']);
$updateQuery = "UPDATE pages SET code = '$newContent' WHERE name = '$pageToSave'";
mysqli_query($LINK, $updateQuery);
}
// Get the list of pages for the dropdown
$query = "SELECT name FROM pages";
$result = mysqli_query($LINK, $query);
$pages = [];
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$pages[] = $row['name'];
}
}
// Determine which page is selected
$selectedPage = isset($_POST['DATA_page']) ? $_POST['DATA_page'] : ($pages[0] ?? '');
$selectedPageEscaped = mysqli_real_escape_string($LINK, $selectedPage);
// Fetch the content of the selected page
$query2 = "SELECT code FROM pages WHERE name = '$selectedPageEscaped' LIMIT 1";
$result2 = mysqli_query($LINK, $query2);
$content = '';
if ($result2 && mysqli_num_rows($result2) > 0) {
$row2 = mysqli_fetch_assoc($result2);
$content = $row2['code'];
} else {
$content = "No content available.";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CMS Editor</title>
</head>
<body>
<h1>CMS Editor</h1>
<p>Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>. <a href="logout.php">Logout</a></p>
<form action="cms.php" method="POST" id="form">
<select name="DATA_page" onchange="document.getElementById('form').submit();">
<?php
foreach ($pages as $p) {
echo '<option value="' . $p . '"';
if ($p === $selectedPage) echo ' selected';
echo '>' . $p . '</option>';
}
?>
</select>
<br><br>
<textarea name="DATA_content" rows="10" cols="50"><?php echo htmlspecialchars($content); ?></textarea>
<br><br>
<button type="submit" name="BUTTON_save">Save</button>
</form>
</body>
</html>