903 lines
32 KiB
PHP
903 lines
32 KiB
PHP
<?php
|
|
|
|
ini_set('display_errors', '1');
|
|
ini_set('display_startup_errors', '1');
|
|
error_reporting(E_ALL);
|
|
|
|
session_start();
|
|
|
|
include("config.php");
|
|
|
|
if (!isset($ServerName)) {
|
|
http_response_code(403);
|
|
exit();
|
|
}
|
|
|
|
$conn = sqlsrv_connect($ServerName, $ConnectionInfo);
|
|
if ($conn === false) {
|
|
die(print_r(sqlsrv_errors(), true));
|
|
}
|
|
/* ---------------- AJAX Change Row Check ------------------- */
|
|
if (isset($_POST['action']) && in_array($_POST['action'], ['updateRow', 'insertRow', 'deleteRow'])) {
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
|
|
$admin_pass = $_POST['admin_pass'] ?? "";
|
|
if ($admin_pass !== $changeDataInSQLPassword) {
|
|
echo json_encode(['error' => 'Falsches Admin Passwort!']);
|
|
exit;
|
|
}
|
|
}
|
|
/* ---------------- AJAX Update Row ------------------- */
|
|
if (isset($_POST['action']) && $_POST['action'] === 'updateRow') {
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
|
|
$table = $_POST['table'];
|
|
$primaryKey = $_POST['primaryKey'];
|
|
$primaryValue = $_POST['primaryValue'];
|
|
$data = json_decode($_POST['data'], true);
|
|
|
|
$result = updateRow($conn, $table, $primaryKey, $primaryValue, $data);
|
|
|
|
sqlsrv_close($conn);
|
|
echo json_encode($result);
|
|
exit;
|
|
}
|
|
/* ---------------- AJAX Add new Row ------------------- */
|
|
if (isset($_POST['action']) && $_POST['action'] === 'insertRow') {
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
|
|
$table = $_POST['table'];
|
|
$data = json_decode($_POST['data'], true);
|
|
|
|
$result = insertRow($conn, $table, $data);
|
|
|
|
sqlsrv_close($conn);
|
|
echo json_encode($result);
|
|
exit;
|
|
}
|
|
/* ---------------- AJAX delete Row ------------------- */
|
|
if (isset($_POST['action']) && $_POST['action'] === 'deleteRow') {
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
|
|
$table = $_POST['table'];
|
|
$primaryKey = $_POST['primaryKey'];
|
|
$primaryValue = $_POST['primaryValue'];
|
|
|
|
$result = deleteRow($conn, $table, $primaryKey, $primaryValue);
|
|
|
|
sqlsrv_close($conn);
|
|
echo json_encode($result);
|
|
exit;
|
|
}
|
|
|
|
/* ---------------- Struktur Export ------------------- */
|
|
if (isset($_GET['structure'])) {
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
if (isset($_GET['format'])) {
|
|
if ($_GET['format'] == "sql") {
|
|
echo getDatabaseStructureExport($conn, "sql");
|
|
} else {
|
|
echo getDatabaseStructureExport($conn);
|
|
}
|
|
} else {
|
|
echo getDatabaseStructureExport($conn);
|
|
}
|
|
|
|
sqlsrv_close($conn);
|
|
exit;
|
|
}
|
|
|
|
/* ---------------- Tabellen Export ------------------- */
|
|
if (isset($_GET['export'], $_GET['table'])) {
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
if (isset($_GET['format'])) {
|
|
if ($_GET['format'] == "sql") {
|
|
echo exportTableData($conn, $_GET['table'], "sql");
|
|
} else {
|
|
echo exportTableData($conn, $_GET['table']);
|
|
}
|
|
} else {
|
|
echo exportTableData($conn, $_GET['table']);
|
|
}
|
|
|
|
sqlsrv_close($conn);
|
|
exit;
|
|
}
|
|
|
|
/* ---------------- Funktionen ------------------- */
|
|
|
|
function getDatabaseStructureExport($conn, $format = 'json')
|
|
{
|
|
$tables = getTables($conn);
|
|
$structure = [];
|
|
|
|
foreach ($tables as $table) {
|
|
$query = "
|
|
SELECT
|
|
COLUMN_NAME,
|
|
DATA_TYPE,
|
|
CHARACTER_MAXIMUM_LENGTH,
|
|
IS_NULLABLE,
|
|
COLUMN_DEFAULT
|
|
FROM INFORMATION_SCHEMA.COLUMNS
|
|
WHERE TABLE_NAME = ?;
|
|
";
|
|
|
|
$stmt = sqlsrv_query($conn, $query, [$table]);
|
|
if (!$stmt) continue;
|
|
|
|
$columns = [];
|
|
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
|
$columns[] = [
|
|
'name' => $row['COLUMN_NAME'],
|
|
'type' => $row['DATA_TYPE'],
|
|
'length' => $row['CHARACTER_MAXIMUM_LENGTH'],
|
|
'nullable' => $row['IS_NULLABLE'],
|
|
'default' => $row['COLUMN_DEFAULT']
|
|
];
|
|
}
|
|
|
|
sqlsrv_free_stmt($stmt);
|
|
$structure[$table] = $columns;
|
|
}
|
|
|
|
if ($format === 'array') {
|
|
return $structure;
|
|
}
|
|
if ($format === 'json') {
|
|
return json_encode($structure, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
|
|
}
|
|
if ($format === 'sql') {
|
|
$sqlText = "-- Exportierte Tabellenstruktur\n\n";
|
|
foreach ($structure as $table => $columns) {
|
|
$sqlText .= "CREATE TABLE [$table] (\n";
|
|
$lines = [];
|
|
foreach ($columns as $col) {
|
|
$line = " [{$col['name']}] {$col['type']}";
|
|
if (!is_null($col['length']) && $col['length'] > 0) {
|
|
$line .= "({$col['length']})";
|
|
} elseif ($col['length'] == -1) {
|
|
$line .= "(MAX)";
|
|
}
|
|
$line .= $col['nullable'] === 'NO' ? " NOT NULL" : " NULL";
|
|
if (!is_null($col['default'])) {
|
|
$line .= " DEFAULT {$col['default']}";
|
|
}
|
|
$lines[] = $line;
|
|
}
|
|
$sqlText .= implode(",\n", $lines) . "\n);\n\n";
|
|
}
|
|
return $sqlText;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function exportTableData($conn, $table, $output_format = 'json')
|
|
{
|
|
$query = "SELECT * FROM [$table]";
|
|
$stmt = sqlsrv_query($conn, $query);
|
|
|
|
if (!$stmt) {
|
|
return json_encode(['error' => sqlsrv_errors()], JSON_PRETTY_PRINT);
|
|
}
|
|
|
|
$data = [];
|
|
$insertSQL = '';
|
|
|
|
$columns = [];
|
|
$fieldMeta = sqlsrv_field_metadata($stmt);
|
|
foreach ($fieldMeta as $field) {
|
|
$columns[] = $field['Name'];
|
|
}
|
|
|
|
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
|
if ($output_format === 'json' || $output_format === 'file') {
|
|
foreach ($row as $key => $value) {
|
|
if ($value instanceof DateTime) {
|
|
$row[$key] = $value->format('Y-m-d H:i:s');
|
|
}
|
|
}
|
|
$data[] = $row;
|
|
}
|
|
|
|
if ($output_format === 'sql' || $output_format === 'file') {
|
|
$values = array_map(function ($v) {
|
|
if (is_null($v)) return "NULL";
|
|
if ($v instanceof DateTime) return "'" . $v->format('Y-m-d H:i:s') . "'";
|
|
return "'" . str_replace("'", "''", $v) . "'";
|
|
}, array_values($row));
|
|
|
|
$insertSQL .= "INSERT INTO [$table] (" . implode(", ", $columns) . ") VALUES (" . implode(", ", $values) . ");\n";
|
|
}
|
|
}
|
|
|
|
sqlsrv_free_stmt($stmt);
|
|
|
|
if ($output_format === 'file') {
|
|
$timestamp = date("Ymd_His");
|
|
$dir = __DIR__ . "/db_backup";
|
|
if (!is_dir($dir)) mkdir($dir, 0777, true);
|
|
|
|
$jsonFile = "$dir/{$table}_$timestamp.json";
|
|
$sqlFile = "$dir/{$table}_$timestamp.sql";
|
|
|
|
file_put_contents($jsonFile, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
|
|
file_put_contents($sqlFile, $insertSQL);
|
|
|
|
return json_encode([
|
|
"message" => "Daten gespeichert",
|
|
"json_path" => $jsonFile,
|
|
"sql_path" => $sqlFile
|
|
], JSON_PRETTY_PRINT);
|
|
}
|
|
|
|
if ($output_format === 'json') {
|
|
return json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
|
|
}
|
|
|
|
return $insertSQL;
|
|
}
|
|
|
|
function getTables($conn)
|
|
{
|
|
$query = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE';";
|
|
$stmt = sqlsrv_query($conn, $query);
|
|
$tables = [];
|
|
|
|
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
|
$tables[] = $row['TABLE_NAME'];
|
|
}
|
|
|
|
sqlsrv_free_stmt($stmt);
|
|
return $tables;
|
|
}
|
|
|
|
function getColumns($conn, $table)
|
|
{
|
|
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ?;";
|
|
$stmt = sqlsrv_query($conn, $query, [$table]);
|
|
$columns = [];
|
|
|
|
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
|
$columns[] = $row['COLUMN_NAME'];
|
|
}
|
|
|
|
sqlsrv_free_stmt($stmt);
|
|
return $columns;
|
|
}
|
|
|
|
function getTableData($conn, $table)
|
|
{
|
|
$query = "SELECT * FROM [$table];";
|
|
$stmt = sqlsrv_query($conn, $query);
|
|
$rows = [];
|
|
|
|
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
|
foreach ($row as $key => $value) {
|
|
if ($value instanceof DateTime) {
|
|
$row[$key] = $value->format('Y-m-d H:i:s');
|
|
}
|
|
}
|
|
$rows[] = $row;
|
|
}
|
|
|
|
sqlsrv_free_stmt($stmt);
|
|
return $rows;
|
|
}
|
|
|
|
function executeSQL($conn, $sql, $format = "json", $admin_pass = null, $realPass="", $exporttableName = "") {
|
|
$stmtType = strtoupper(strtok(trim($sql), " ")); // erstes Wort der Query erkennen
|
|
|
|
// Prüfen ob Query eine Änderung macht
|
|
$isWriteQuery = in_array($stmtType, ["INSERT", "UPDATE", "DELETE", "ALTER", "DROP", "CREATE"]);
|
|
|
|
// Falls Schreib-Query und kein gültiges Passwort => sofort Fehler zurück
|
|
if ($isWriteQuery && $admin_pass !== $realPass) {
|
|
return ["error" => "Incorrect admin password for write operations."];
|
|
}
|
|
|
|
$stmt = sqlsrv_query($conn, $sql);
|
|
|
|
if ($stmt === false) {
|
|
return sqlsrv_errors(); // Falls ein Fehler auftritt, gebe die Fehler zurück
|
|
} else {
|
|
$results = [];
|
|
|
|
if ($stmtType === "SELECT") {
|
|
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) { $results[] = $row; }
|
|
|
|
// === JSON Export (Direkter Download) ===
|
|
if ($format === "json_download") {
|
|
// JSON-String erzeugen
|
|
$jsonData = json_encode($results, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
|
|
|
|
// Header für JSON-Download
|
|
header("Content-Type: application/json; charset=utf-8");
|
|
header("Content-Disposition: attachment; filename=" . $exporttableName . ".json");
|
|
header("Pragma: no-cache");
|
|
header("Expires: 0");
|
|
|
|
echo $jsonData;
|
|
sqlsrv_free_stmt($stmt);
|
|
exit; // wichtig: Skript beenden
|
|
}
|
|
|
|
// === BACKUP_SQL ===
|
|
if ($format === "backup_sql") {
|
|
$meta = sqlsrv_field_metadata($stmt);
|
|
if ($meta === false) {
|
|
return "Fehler beim Lesen der Feld-Metadaten.";
|
|
}
|
|
|
|
$create = "CREATE TABLE [$exporttableName] (\n";
|
|
$cols = [];
|
|
foreach ($meta as $field) {
|
|
$colName = $field['Name'];
|
|
switch ($field['Type']) {
|
|
case SQLSRV_SQLTYPE_INT:
|
|
case SQLSRV_SQLTYPE_BIGINT:
|
|
case SQLSRV_SQLTYPE_SMALLINT:
|
|
$colType = "INT";
|
|
break;
|
|
case SQLSRV_SQLTYPE_BIT:
|
|
$colType = "BIT";
|
|
break;
|
|
case SQLSRV_SQLTYPE_FLOAT:
|
|
case SQLSRV_SQLTYPE_REAL:
|
|
$colType = "FLOAT";
|
|
break;
|
|
case SQLSRV_SQLTYPE_DATETIME:
|
|
case SQLSRV_SQLTYPE_DATETIME2:
|
|
case SQLSRV_SQLTYPE_DATE:
|
|
$colType = "DATETIME";
|
|
break;
|
|
default:
|
|
$colType = "NVARCHAR(MAX)";
|
|
break;
|
|
}
|
|
$cols[] = " [$colName] $colType";
|
|
}
|
|
$create .= implode(",\n", $cols) . "\n);\n\n";
|
|
|
|
$inserts = "";
|
|
foreach ($results as $row) {
|
|
$values = [];
|
|
foreach ($row as $val) {
|
|
if ($val === null) {
|
|
$values[] = "NULL";
|
|
} elseif (is_numeric($val)) {
|
|
$values[] = $val;
|
|
} elseif ($val instanceof DateTime) {
|
|
$values[] = "'" . $val->format("Y-m-d H:i:s") . "'";
|
|
} else {
|
|
$values[] = "'" . str_replace("'", "''", $val) . "'";
|
|
}
|
|
}
|
|
$inserts .= "INSERT INTO [$exporttableName] VALUES (" . implode(", ", $values) . ");\n";
|
|
}
|
|
|
|
sqlsrv_free_stmt($stmt);
|
|
return $create . $inserts;
|
|
}
|
|
|
|
// === BACKUP_SQL Export (Direkter Download) ===
|
|
if ($format === "backup_sql_download") {
|
|
$meta = sqlsrv_field_metadata($stmt);
|
|
if ($meta === false) {
|
|
return "Fehler beim Lesen der Feld-Metadaten.";
|
|
}
|
|
|
|
$tableName = "ExportTable";
|
|
$create = "CREATE TABLE [$tableName] (\n";
|
|
$cols = [];
|
|
|
|
foreach ($meta as $field) {
|
|
$colName = $field['Name'];
|
|
switch ($field['Type']) {
|
|
case SQLSRV_SQLTYPE_INT:
|
|
case SQLSRV_SQLTYPE_BIGINT:
|
|
case SQLSRV_SQLTYPE_SMALLINT:
|
|
$colType = "INT";
|
|
break;
|
|
case SQLSRV_SQLTYPE_BIT:
|
|
$colType = "BIT";
|
|
break;
|
|
case SQLSRV_SQLTYPE_FLOAT:
|
|
case SQLSRV_SQLTYPE_REAL:
|
|
$colType = "FLOAT";
|
|
break;
|
|
case SQLSRV_SQLTYPE_DATETIME:
|
|
case SQLSRV_SQLTYPE_DATETIME2:
|
|
case SQLSRV_SQLTYPE_DATE:
|
|
$colType = "DATETIME";
|
|
break;
|
|
default:
|
|
$colType = "NVARCHAR(MAX)";
|
|
break;
|
|
}
|
|
$cols[] = " [$colName] $colType";
|
|
}
|
|
$create .= implode(",\n", $cols) . "\n);\n\n";
|
|
|
|
$inserts = "";
|
|
foreach ($results as $row) {
|
|
$values = [];
|
|
foreach ($row as $val) {
|
|
if ($val === null) {
|
|
$values[] = "NULL";
|
|
} elseif (is_numeric($val)) {
|
|
$values[] = $val;
|
|
} elseif ($val instanceof DateTime) {
|
|
$values[] = "'" . $val->format("Y-m-d H:i:s") . "'";
|
|
} else {
|
|
$values[] = "'" . str_replace("'", "''", $val) . "'";
|
|
}
|
|
}
|
|
$inserts .= "INSERT INTO [$tableName] VALUES (" . implode(", ", $values) . ");\n";
|
|
}
|
|
|
|
$sqlDump = $create . $inserts;
|
|
|
|
// Header für SQL-Download
|
|
header("Content-Type: application/sql; charset=utf-8");
|
|
header("Content-Disposition: attachment; filename=" . $exporttableName . ".sql");
|
|
header("Pragma: no-cache");
|
|
header("Expires: 0");
|
|
|
|
echo $sqlDump;
|
|
sqlsrv_free_stmt($stmt);
|
|
exit; // wichtig: beenden
|
|
}
|
|
|
|
// === CSV ===
|
|
if ($format === "csv") {
|
|
if (empty($results)) {
|
|
return "";
|
|
}
|
|
$output = "";
|
|
$headers = array_keys($results[0]);
|
|
$output .= implode(";", $headers) . "\n";
|
|
foreach ($results as $row) {
|
|
$escaped = array_map(function($val) {
|
|
if ($val === null) return "";
|
|
$val = str_replace('"', '""', $val);
|
|
return '"' . $val . '"';
|
|
}, $row);
|
|
$output .= implode(";", $escaped) . "\n";
|
|
}
|
|
sqlsrv_free_stmt($stmt);
|
|
return $output;
|
|
}
|
|
|
|
// === EXCEL Export / EXCEL-HTML (Direkter Download) ===
|
|
if ($format === "excel_download") {
|
|
if (empty($results)) {
|
|
return "";
|
|
}
|
|
|
|
$headers = array_keys($results[0]);
|
|
|
|
$output = "<table border='1'><tr>";
|
|
foreach ($headers as $header) {
|
|
$output .= "<th>" . htmlspecialchars($header) . "</th>";
|
|
}
|
|
$output .= "</tr>";
|
|
|
|
foreach ($results as $row) {
|
|
$output .= "<tr>";
|
|
foreach ($headers as $header) {
|
|
$val = $row[$header];
|
|
if ($val instanceof DateTime) {
|
|
$val = $val->format("Y-m-d H:i:s");
|
|
}
|
|
$output .= "<td>" . htmlspecialchars((string)$val) . "</td>";
|
|
}
|
|
$output .= "</tr>";
|
|
}
|
|
$output .= "</table>";
|
|
|
|
// Header für Excel-Download
|
|
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
|
|
header("Content-Disposition: attachment; filename=" . $exporttableName . ".xls");
|
|
header("Pragma: no-cache");
|
|
header("Expires: 0");
|
|
|
|
echo $output;
|
|
sqlsrv_free_stmt($stmt);
|
|
exit; // Wichtig: Script nach Download beenden
|
|
}
|
|
|
|
// === CSV Export (Direkter Download) ===
|
|
if ($format === "csv_download") {
|
|
if (empty($results)) {
|
|
return "";
|
|
}
|
|
|
|
// CSV erzeugen
|
|
$headers = array_keys($results[0]);
|
|
$output = implode(";", $headers) . "\n";
|
|
|
|
foreach ($results as $row) {
|
|
$escaped = array_map(function($val) {
|
|
if ($val === null) return "";
|
|
if ($val instanceof DateTime) {
|
|
$val = $val->format("Y-m-d H:i:s");
|
|
}
|
|
$val = str_replace('"', '""', $val); // Doppelte Anführungszeichen escapen
|
|
return '"' . $val . '"';
|
|
}, $row);
|
|
|
|
$output .= implode(";", $escaped) . "\n";
|
|
}
|
|
|
|
// Header für CSV-Download
|
|
header("Content-Type: text/csv; charset=utf-8");
|
|
header("Content-Disposition: attachment; filename=" . $exporttableName . ".csv");
|
|
header("Pragma: no-cache");
|
|
header("Expires: 0");
|
|
|
|
echo $output;
|
|
sqlsrv_free_stmt($stmt);
|
|
exit; // Wichtig: Skript nach Download beenden
|
|
}
|
|
|
|
// === Default (Array) ===
|
|
sqlsrv_free_stmt($stmt);
|
|
return $results;
|
|
} else {
|
|
// Schreibende Query (hier Passwort schon vorher geprüft)
|
|
$affectedRows = sqlsrv_rows_affected($stmt);
|
|
sqlsrv_free_stmt($stmt);
|
|
return "Anzahl der betroffenen Zeilen: " . $affectedRows;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* -------- Update Row Funktion -------- */
|
|
function updateRow($conn, $table, $primaryKey, $primaryValue, $data)
|
|
{
|
|
$setParts = [];
|
|
$params = [];
|
|
foreach ($data as $col => $val) {
|
|
$setParts[] = "[$col] = ?";
|
|
$params[] = $val;
|
|
}
|
|
|
|
$setSQL = implode(", ", $setParts);
|
|
$params[] = $primaryValue;
|
|
|
|
$sql = "UPDATE [$table] SET $setSQL WHERE [$primaryKey] = ?";
|
|
|
|
$stmt = sqlsrv_query($conn, $sql, $params);
|
|
|
|
if ($stmt === false) {
|
|
return ['error' => sqlsrv_errors()];
|
|
}
|
|
|
|
sqlsrv_free_stmt($stmt);
|
|
return ['success' => true];
|
|
}
|
|
|
|
/* -------- Add new Row Funktion -------- */
|
|
function insertRow($conn, $table, $data)
|
|
{
|
|
$columns = array_keys($data);
|
|
$params = [];
|
|
$placeholders = [];
|
|
|
|
foreach ($columns as $col) {
|
|
$val = $data[$col];
|
|
|
|
if (strtoupper(trim($val)) === "NEWID()") {
|
|
// SQL-Befehl direkt einfügen
|
|
$placeholders[] = "NEWID()";
|
|
} else {
|
|
$placeholders[] = "?";
|
|
$params[] = $val;
|
|
}
|
|
}
|
|
|
|
$colList = implode(", ", array_map(fn($c) => "[$c]", $columns));
|
|
$placeholdersSql = implode(", ", $placeholders);
|
|
|
|
$sql = "INSERT INTO [$table] ($colList) VALUES ($placeholdersSql)";
|
|
$stmt = sqlsrv_query($conn, $sql, $params);
|
|
|
|
if ($stmt === false) {
|
|
return ['error' => sqlsrv_errors()];
|
|
}
|
|
|
|
sqlsrv_free_stmt($stmt);
|
|
return ['success' => true];
|
|
}
|
|
|
|
/* -------- Delete Row Funktion -------- */
|
|
function deleteRow($conn, $table, $primaryKey, $primaryValue)
|
|
{
|
|
$sql = "DELETE FROM [$table] WHERE [$primaryKey] = ?";
|
|
$stmt = sqlsrv_query($conn, $sql, [$primaryValue]);
|
|
|
|
if ($stmt === false) {
|
|
return ['error' => sqlsrv_errors()];
|
|
}
|
|
|
|
sqlsrv_free_stmt($stmt);
|
|
return ['success' => true];
|
|
}
|
|
|
|
/* ----------------- SQL Executor (gekürzt) ----------------- */
|
|
|
|
$tables = getTables($conn);
|
|
sort($tables);
|
|
$currentTable = $_GET['table'] ?? null;
|
|
$tableData = $currentTable ? getTableData($conn, $currentTable) : [];
|
|
$tableColumns = $currentTable ? getColumns($conn, $currentTable) : [];
|
|
|
|
$resultMessage = null;
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sql_query'])) {
|
|
$sqlQuery = $_POST['sql_query'];
|
|
$returnformat = "json";
|
|
$adminPass = "";
|
|
$exportTabelName = "ExportTable" . rand();
|
|
if (isset($_POST['format'])) {
|
|
$returnformat = $_POST['format'];
|
|
}
|
|
if (isset($_POST['admin_pass'])) {
|
|
$adminPass = $_POST['admin_pass'];
|
|
}
|
|
if (!empty($_POST['exporttabelName'])) {
|
|
$exportTabelName = $_POST['exporttabelName'];
|
|
}
|
|
$resultMessage = executeSQL($conn, $sqlQuery, $returnformat, $adminPass, $changeDataInSQLPassword, $exportTabelName);
|
|
}
|
|
|
|
sqlsrv_close($conn);
|
|
?>
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>SQL-WebStudio</title>
|
|
<style>
|
|
body { font-family: Arial, sans-serif; display: flex; }
|
|
/* #sidebar { width: 250px; background-color: #f0f0f0; padding: 20px; height: 100vh; overflow-y: auto; }*/
|
|
#content { flex-grow: 1; padding: 20px; }
|
|
table { border-collapse: collapse; width: 100%; margin-top: 20px; }
|
|
th, td { padding: 8px; border: 1px solid #ddd; }
|
|
th { background-color: #f2f2f2; }
|
|
a { text-decoration: none; color: blue; }
|
|
textarea { width: 100%; height: 150px; margin-top: 10px; }
|
|
.navbar { background-color: #007bff; padding: 10px; color: white; }
|
|
.navbar a { color: white; margin-right: 10px; }
|
|
.save-row { background: #28a745; color: white; border: none; padding: 5px 10px; cursor: pointer; }
|
|
.add-row { background: blue; color: white; border: none; padding: 5px 10px; cursor: pointer; }
|
|
.delete-row { background: red; color: white; border: none; padding: 5px 10px; cursor: pointer; margin-top: 2px; }
|
|
#sidebar {
|
|
flex-shrink: 0;
|
|
min-width: 250px;
|
|
max-width: 250px;
|
|
box-sizing: border-box;
|
|
}
|
|
#sidebar {
|
|
width: 250px;
|
|
background-color: #f0f0f0;
|
|
padding: 20px;
|
|
height: 100vh;
|
|
position: sticky;
|
|
top: 0;
|
|
overflow-y: auto;
|
|
}
|
|
#data-table td:first-child,
|
|
#data-table th:first-child {
|
|
text-align: center;
|
|
width: 50px;
|
|
}
|
|
#data-table {
|
|
border-collapse: collapse;
|
|
width: 100%;
|
|
}
|
|
|
|
#data-table th {
|
|
position: sticky;
|
|
top: 0;
|
|
background: #f2f2f2;
|
|
z-index: 2;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
|
|
<div id="sidebar">
|
|
<div style="margin:10px 0;">
|
|
<input type="password" id="admin-pass" placeholder="Admin Passwort" />
|
|
</div>
|
|
<h2>Tabellen</h2>
|
|
<ul>
|
|
<?php foreach ($tables as $table): ?>
|
|
<li><a href="?table=<?= $table ?>"><?= $table ?></a></li>
|
|
<?php endforeach; ?>
|
|
</ul>
|
|
</div>
|
|
|
|
<div id="content">
|
|
<div class="navbar">
|
|
<a href="?">Home</a>
|
|
<a href="?sql=1">SQL</a>
|
|
</div>
|
|
|
|
<?php if ($currentTable): ?>
|
|
<h2>Tabelle: <?= htmlspecialchars($currentTable) ?></h2>
|
|
<table id="data-table">
|
|
<thead>
|
|
<tr>
|
|
<th>#</th>
|
|
<?php foreach ($tableColumns as $column): ?>
|
|
<th><?= htmlspecialchars($column) ?></th>
|
|
<?php endforeach; ?>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
<!-- Neue Zeile hinzufügen -->
|
|
<tr class="new-row">
|
|
<td><button class="add-row">Add</button></td>
|
|
<?php foreach ($tableColumns as $index => $column): ?>
|
|
<!--<td contenteditable="<?= $index === 0 ? 'false' : 'true' ?>"
|
|
data-column="<?= htmlspecialchars($column) ?>">
|
|
</td>-->
|
|
<td contenteditable="true" data-column="<?= htmlspecialchars($column) ?>"></td>
|
|
<?php endforeach; ?>
|
|
</tr>
|
|
<?php $rowNumber = 1; ?>
|
|
<?php foreach ($tableData as $row): ?>
|
|
<tr data-pk="<?= htmlspecialchars($row[$tableColumns[0]]) ?>">
|
|
<td><?= $rowNumber++; ?><br/><button class="save-row">Save</button><br/><button class="delete-row">Delete</button></td>
|
|
<?php foreach ($tableColumns as $index => $column): ?>
|
|
<td contenteditable="<?= $index === 0 ? 'false' : 'true' ?>"
|
|
data-column="<?= htmlspecialchars($column) ?>">
|
|
<?= htmlspecialchars($row[$column] ?? '') ?>
|
|
</td>
|
|
<?php endforeach; ?>
|
|
</tr>
|
|
<?php endforeach; ?>
|
|
|
|
</tbody>
|
|
</table>
|
|
|
|
<script>
|
|
document.addEventListener('DOMContentLoaded', function () {
|
|
|
|
//Zeiele bearbeiten
|
|
document.querySelectorAll('.save-row').forEach(btn => {
|
|
btn.addEventListener('click', function () {
|
|
const adminPass = document.getElementById('admin-pass').value || "";
|
|
const row = this.closest('tr');
|
|
const pkValue = row.dataset.pk;
|
|
const cells = row.querySelectorAll('td[data-column]');
|
|
const data = {};
|
|
|
|
cells.forEach(cell => {
|
|
data[cell.dataset.column] = cell.innerText.trim();
|
|
});
|
|
|
|
fetch('', {
|
|
method: 'POST',
|
|
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
|
|
body: new URLSearchParams({
|
|
action: 'updateRow',
|
|
table: "<?= $currentTable ?>",
|
|
primaryKey: "<?= $tableColumns[0] ?>",
|
|
primaryValue: pkValue,
|
|
data: JSON.stringify(data),
|
|
admin_pass: adminPass
|
|
})
|
|
})
|
|
.then(res => res.json())
|
|
.then(response => {
|
|
if (response.success) {
|
|
alert("Zeile gespeichert!");
|
|
} else {
|
|
alert("Fehler: " + JSON.stringify(response.error));
|
|
}
|
|
});
|
|
});
|
|
});
|
|
|
|
// Neue Zeile einfügen
|
|
const addBtn = document.querySelector('.add-row');
|
|
if (addBtn) {
|
|
addBtn.addEventListener('click', function () {
|
|
const adminPass = document.getElementById('admin-pass').value || "";
|
|
const row = this.closest('tr');
|
|
const cells = row.querySelectorAll('td[data-column]');
|
|
const data = {};
|
|
|
|
cells.forEach(cell => {
|
|
if (cell.contentEditable === "true" && cell.innerText.trim() !== "") {
|
|
data[cell.dataset.column] = cell.innerText.trim();
|
|
}
|
|
});
|
|
|
|
fetch('', {
|
|
method: 'POST',
|
|
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
|
|
body: new URLSearchParams({
|
|
action: 'insertRow',
|
|
table: "<?= $currentTable ?>",
|
|
data: JSON.stringify(data),
|
|
admin_pass: adminPass
|
|
})
|
|
})
|
|
.then(res => res.json())
|
|
.then(response => {
|
|
if (response.success) {
|
|
alert("Neue Zeile eingefügt!");
|
|
location.reload(); // Tabelle neu laden
|
|
} else {
|
|
alert("Fehler: " + JSON.stringify(response.error));
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
// Zeile löschen
|
|
document.querySelectorAll('.delete-row').forEach(btn => {
|
|
btn.addEventListener('click', function () {
|
|
if (!confirm("Diese Zeile wirklich löschen?")) return;
|
|
const adminPass = document.getElementById('admin-pass').value || "";
|
|
const row = this.closest('tr');
|
|
const pkValue = row.dataset.pk;
|
|
|
|
fetch('', {
|
|
method: 'POST',
|
|
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
|
|
body: new URLSearchParams({
|
|
action: 'deleteRow',
|
|
table: "<?= $currentTable ?>",
|
|
primaryKey: "<?= $tableColumns[0] ?>",
|
|
primaryValue: pkValue,
|
|
admin_pass: adminPass
|
|
})
|
|
})
|
|
.then(res => res.json())
|
|
.then(response => {
|
|
if (response.success) {
|
|
alert("Zeile gelöscht!");
|
|
row.remove();
|
|
} else {
|
|
alert("Fehler: " + JSON.stringify(response.error));
|
|
}
|
|
});
|
|
});
|
|
});
|
|
});
|
|
</script>
|
|
<?php endif; ?>
|
|
|
|
<?php if (isset($_GET['sql'])): ?>
|
|
<h2>SQL Query Executor</h2>
|
|
<form method="post">
|
|
<textarea name="sql_query" placeholder="Gib dein SQL-Statement hier ein..."><?php if (isset($_POST['sql_query'])){ echo $_POST['sql_query']; } ?></textarea><br>
|
|
<select name="format">
|
|
<option value="json">JSON Anzeige</option>
|
|
<option value="json_download">JSON Download</option>
|
|
<option value="csv">CSV Anzeige</option>
|
|
<option value="csv_download">CSV Download</option>
|
|
<option value="excel_download">Excel Download</option>
|
|
<option value="backup_sql">SQL Anzeige</option>
|
|
<option value="backup_sql_download">SQL Download</option>
|
|
</select>
|
|
<input type="password" id="sqlAdminPass" name="admin_pass" placeholder="SQL Admin Password"/>
|
|
<input type="text" name="exporttabelName" placeholder="Exportname" value="<?php if(isset($_POST['exporttabelName'])){ echo $_POST['exporttabelName']; } ?>" />
|
|
<button type="submit">SQL ausführen</button>
|
|
</form>
|
|
|
|
<?php if ($resultMessage): ?>
|
|
<h3>Ergebnis:</h3>
|
|
<pre><?= is_array($resultMessage) ? print_r(json_encode($resultMessage, JSON_PRETTY_PRINT), true) : htmlspecialchars($resultMessage) ?></pre>
|
|
<?php endif; ?>
|
|
|
|
<?php endif; ?>
|
|
</div>
|
|
|
|
</body>
|
|
</html>
|