From 5f124aec30eac09c788d755b6502255d822baf7a Mon Sep 17 00:00:00 2001 From: olinet Date: Sun, 28 Sep 2025 09:33:45 +0200 Subject: [PATCH] AddOn/SQL-ManagmentStudio_Online/index.php aktualisiert --- AddOn/SQL-ManagmentStudio_Online/index.php | 700 ++++++++++----------- 1 file changed, 346 insertions(+), 354 deletions(-) diff --git a/AddOn/SQL-ManagmentStudio_Online/index.php b/AddOn/SQL-ManagmentStudio_Online/index.php index ab9d1041..db44ee96 100644 --- a/AddOn/SQL-ManagmentStudio_Online/index.php +++ b/AddOn/SQL-ManagmentStudio_Online/index.php @@ -6,62 +6,108 @@ error_reporting(E_ALL); session_start(); -/**************** Servername\Instance ****************/ - $ServerName = ", "; - $changeDataInSQLPassword = "XXXXX"; -/**************** Cathalog\User ****************/ - $ConnectionInfo = array( "Database"=>"...", - "UID"=>"...", - "PWD"=>"...", - "Encrypt"=>false, - "TrustServerCertificate"=>false, - "CharacterSet" => "UTF-8"); +include("config.php"); -/********************************************************/ - - -if(!isset($ServerName)){ http_response_code(403); exit(); } +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"){ + if (isset($_GET['format'])) { + if ($_GET['format'] == "sql") { echo getDatabaseStructureExport($conn, "sql"); - }else{ + } else { echo getDatabaseStructureExport($conn); } - }else{ + } 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"){ + if (isset($_GET['format'])) { + if ($_GET['format'] == "sql") { echo exportTableData($conn, $_GET['table'], "sql"); - }else{ + } else { echo exportTableData($conn, $_GET['table']); } - }else{ + } else { echo exportTableData($conn, $_GET['table']); } - + sqlsrv_close($conn); exit; } +/* ---------------- Funktionen ------------------- */ - -function getDatabaseStructureExport($conn, $format = 'json') { +function getDatabaseStructureExport($conn, $format = 'json') +{ $tables = getTables($conn); $structure = []; @@ -95,23 +141,17 @@ function getDatabaseStructureExport($conn, $format = 'json') { $structure[$table] = $columns; } - // Ausgabe als JSON if ($format === 'array') { return $structure; } - - // Ausgabe als JSON if ($format === 'json') { return json_encode($structure, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); } - - // Ausgabe als SQL CREATE TABLE Statements 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) { @@ -125,18 +165,15 @@ function getDatabaseStructureExport($conn, $format = 'json') { } $lines[] = $line; } - $sqlText .= implode(",\n", $lines) . "\n);\n\n"; } - return $sqlText; } - return null; } -/* -function exportTableData($conn, $table, $output_format = 'json') { +function exportTableData($conn, $table, $output_format = 'json') +{ $query = "SELECT * FROM [$table]"; $stmt = sqlsrv_query($conn, $query); @@ -147,67 +184,13 @@ function exportTableData($conn, $table, $output_format = 'json') { $data = []; $insertSQL = ''; - // Hol dir die Spaltennamen $columns = []; $fieldMeta = sqlsrv_field_metadata($stmt); foreach ($fieldMeta as $field) { $columns[] = $field['Name']; } - // Geh alle Zeilen durch while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) { - // Für JSON-Export - if ($output_format === 'json') { - foreach ($row as $key => $value) { - if ($value instanceof DateTime) { - $row[$key] = $value->format('Y-m-d H:i:s'); - } - } - $data[] = $row; - } - - // Für SQL-Export - if ($output_format === 'sql') { - $values = array_map(function ($v) use ($conn) { - 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 === 'json') { - return json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); - } - - return $insertSQL; -} -*/ -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 = ''; - - // Spaltennamen holen - $columns = []; - $fieldMeta = sqlsrv_field_metadata($stmt); - foreach ($fieldMeta as $field) { - $columns[] = $field['Name']; - } - - // Zeilen verarbeiten - while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) { - // JSON-Darstellung if ($output_format === 'json' || $output_format === 'file') { foreach ($row as $key => $value) { if ($value instanceof DateTime) { @@ -217,7 +200,6 @@ function exportTableData($conn, $table, $output_format = 'json') { $data[] = $row; } - // SQL-Darstellung if ($output_format === 'sql' || $output_format === 'file') { $values = array_map(function ($v) { if (is_null($v)) return "NULL"; @@ -231,7 +213,6 @@ function exportTableData($conn, $table, $output_format = 'json') { sqlsrv_free_stmt($stmt); - // Ausgabe als Datei auf dem Server if ($output_format === 'file') { $timestamp = date("Ymd_His"); $dir = __DIR__ . "/db_backup"; @@ -240,7 +221,6 @@ function exportTableData($conn, $table, $output_format = 'json') { $jsonFile = "$dir/{$table}_$timestamp.json"; $sqlFile = "$dir/{$table}_$timestamp.sql"; - // Beide Formate speichern file_put_contents($jsonFile, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); file_put_contents($sqlFile, $insertSQL); @@ -251,7 +231,6 @@ function exportTableData($conn, $table, $output_format = 'json') { ], JSON_PRETTY_PRINT); } - // Direkt anzeigen if ($output_format === 'json') { return json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); } @@ -259,8 +238,8 @@ function exportTableData($conn, $table, $output_format = 'json') { return $insertSQL; } - -function getTables($conn) { +function getTables($conn) +{ $query = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE';"; $stmt = sqlsrv_query($conn, $query); $tables = []; @@ -273,7 +252,8 @@ function getTables($conn) { return $tables; } -function getColumns($conn, $table) { +function getColumns($conn, $table) +{ $query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ?;"; $stmt = sqlsrv_query($conn, $query, [$table]); $columns = []; @@ -286,16 +266,16 @@ function getColumns($conn, $table) { return $columns; } -function getTableData($conn, $table) { +function getTableData($conn, $table) +{ $query = "SELECT * FROM [$table];"; $stmt = sqlsrv_query($conn, $query); $rows = []; while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) { - // $rows[] = $row; - foreach ($row as $key => $value) { + foreach ($row as $key => $value) { if ($value instanceof DateTime) { - $row[$key] = $value->format('Y-m-d H:i:s'); // Oder jedes gewünschte Format + $row[$key] = $value->format('Y-m-d H:i:s'); } } $rows[] = $row; @@ -305,67 +285,6 @@ function getTableData($conn, $table) { return $rows; } -/* -function executeSQL($conn, $sql) { - $stmt = sqlsrv_query($conn, $sql); - if ($stmt === false) { - return sqlsrv_errors(); - }else{ - - } - sqlsrv_free_stmt($stmt); - return "Query erfolgreich ausgeführt."; -}*/ -/* -function executeSQL($conn, $sql, $format = "json") { - $stmt = sqlsrv_query($conn, $sql); - - if ($stmt === false) { - return sqlsrv_errors(); // Falls ein Fehler auftritt, gebe die Fehler zurück - } else { - $results = []; - if (strpos(strtoupper($sql), 'SELECT') !== false) { - // Nur bei SELECT-Abfragen die Ergebnisse holen - while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) { - $results[] = $row; - } - sqlsrv_free_stmt($stmt); - - if ($format === "csv") { - if (empty($results)) { - return ""; // keine Daten - } - // CSV-String erstellen - $output = ""; - // Header-Zeile mit Spaltennamen - $headers = array_keys($results[0]); - $output .= implode(";", $headers) . "\n"; - - // Datenzeilen - foreach ($results as $row) { - // Werte ggf. mit Anführungszeichen escapen - $escaped = array_map(function($val) { - if ($val === null) return ""; - $val = str_replace('"', '""', $val); // Doppelte Quotes für CSV - return '"' . $val . '"'; - }, $row); - $output .= implode(";", $escaped) . "\n"; - } - return $output; - } else { - // Standard = Array zurückgeben (kann mit json_encode nach JSON gewandelt werden) - return $results; - } - } else { - // Bei INSERT, UPDATE, DELETE etc. die Anzahl der betroffenen Zeilen zurückgeben - $affectedRows = sqlsrv_rows_affected($stmt); - sqlsrv_free_stmt($stmt); - return "Anzahl der betroffenen Zeilen: " . $affectedRows; - } - } -} -*/ - function executeSQL($conn, $sql, $format = "json", $admin_pass = null, $realPass="", $exporttableName = "") { $stmtType = strtoupper(strtok(trim($sql), " ")); // erstes Wort der Query erkennen @@ -634,10 +553,82 @@ function executeSQL($conn, $sql, $format = "json", $admin_pass = null, $realPass } } +/* -------- 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); // Tabellen alphabetisch sortieren +sort($tables); $currentTable = $_GET['table'] ?? null; $tableData = $currentTable ? getTableData($conn, $currentTable) : []; $tableColumns = $currentTable ? getColumns($conn, $currentTable) : []; @@ -647,10 +638,16 @@ 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']; } + $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); } @@ -662,7 +659,7 @@ sqlsrv_close($conn); SQL-WebStudio - -

Tabelle:

- - - - - - - - - - - - - - - - -
#
- - - +

Tabelle:

@@ -726,184 +734,168 @@ sqlsrv_close($conn); - - - - - - + + + + $column): ?> + + + + - - - - + + + $column): ?> + +


+ +
- - - -

Tabelle:

-
- - - - - - - - - - - - - - - - - - - - - - - - - - -
#
-
-
- - - - - - - - -

SQL Query Executor

-
-
- - - - -
- - -

Ergebnis:

-
- + + // 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: "", + 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: "", + primaryKey: "", + 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)); + } + }); + }); + }); + }); + + + + +

SQL Query Executor

+
+
+ + + + +
+ + +

Ergebnis:

+
+ +