DSB-PlugIn/AddOn/SQL-ManagmentStudio_Online/index.php

752 lines
25 KiB
PHP

<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
session_start();
/**************** Servername\Instance ****************/
$ServerName = "<MS SQL Server>, <Port>";
$changeDataInSQLPassword = "XXXXX";
/**************** Cathalog\User ****************/
$ConnectionInfo = array( "Database"=>"...",
"UID"=>"...",
"PWD"=>"...",
"Encrypt"=>false,
"TrustServerCertificate"=>false,
"CharacterSet" => "UTF-8");
/********************************************************/
if(!isset($ServerName)){ http_response_code(403); exit(); }
$conn = sqlsrv_connect($ServerName, $ConnectionInfo);
if ($conn === false) {
die(print_r(sqlsrv_errors(), true));
}
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;
}
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;
}
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;
}
// 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) {
$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 = '';
// 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) {
$row[$key] = $value->format('Y-m-d H:i:s');
}
}
$data[] = $row;
}
// SQL-Darstellung
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);
// Ausgabe als Datei auf dem Server
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";
// Beide Formate speichern
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);
}
// Direkt anzeigen
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)) {
// $rows[] = $row;
foreach ($row as $key => $value) {
if ($value instanceof DateTime) {
$row[$key] = $value->format('Y-m-d H:i:s'); // Oder jedes gewünschte Format
}
}
$rows[] = $row;
}
sqlsrv_free_stmt($stmt);
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
// 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;
}
// === 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;
}
// === 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;
}
// === 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;
}
}
}
$tables = getTables($conn);
sort($tables); // Tabellen alphabetisch sortieren
$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(isset($_POST['exporttabelName'])){ $exportTabelName = $_POST['exporttabelName']; }
$resultMessage = executeSQL($conn, $sqlQuery, $returnformat, $adminPass, $changeDataInSQLPassword, $exportTabelName);
}
sqlsrv_close($conn);
?>
<!DOCTYPE html>
<html>
<head>
<title>Mini PHPMyAdmin for MSSQL</title>
<style>
body { font-family: Arial, sans-serif; display: flex; }
#sidebar { width: 250px; background-color: #f0f0f0; padding: 20px; height: 100vh; }
#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; }
</style>
</head>
<body>
<div id="sidebar">
<h2>Tabellen</h2>
<?php
// $dbStruckture = getDatabaseStructureExport($conn, 'array');
//echo count($dbStruckture);
?>
<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>
<tr>
<th>#</th> <!-- Neue Spalte für die laufende ID -->
<?php foreach ($tableColumns as $column): ?>
<th><?= htmlspecialchars($column) ?></th>
<?php endforeach; ?>
</tr>
<?php $rowNumber = 1; ?> <!-- Zähler initialisieren -->
<?php foreach ($tableData as $row): ?>
<tr>
<td><?= $rowNumber++; ?></td> <!-- Hochzählende ID einfügen -->
<?php foreach ($tableColumns as $column): ?>
<td><?= htmlspecialchars($row[$column] ?? '') ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
<?php endif; */ ?>
<?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>
<tr>
<th></th> <!-- Platzhalter für die ID-Spalte -->
<?php foreach ($tableColumns as $column): ?>
<th><input type="text" class="column-filter" placeholder="Filtern..."></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php $rowNumber = 1; ?>
<?php foreach ($tableData as $row): ?>
<tr>
<td><?= $rowNumber++; ?></td>
<?php foreach ($tableColumns as $column): ?>
<td><?= htmlspecialchars($row[$column] ?? '') ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<script>
document.addEventListener('DOMContentLoaded', function () {
const filters = document.querySelectorAll('.column-filter');
const table = document.getElementById('data-table');
const rows = Array.from(table.querySelectorAll('tbody tr'));
filters.forEach((filter, index) => {
filter.addEventListener('input', function () {
const filterValue = this.value.toLowerCase();
rows.forEach(row => {
const cell = row.cells[index + 1]; // +1 wegen der ID-Spalte
if (cell) {
const cellText = cell.textContent.toLowerCase();
row.style.display = cellText.includes(filterValue) ? '' : 'none';
}
});
});
});
});
</script>
<?php endif; ?>
<?php /* if ($currentTable): ?>
<h2>Tabelle: <?= htmlspecialchars($currentTable) ?></h2>
<div id="table-container">
<table id="data-table">
<thead>
<tr>
<th>#</th>
<?php foreach ($tableColumns as $column): ?>
<th><?= htmlspecialchars($column) ?></th>
<?php endforeach; ?>
</tr>
<tr>
<th></th> <!-- Platzhalter für die ID-Spalte -->
<?php foreach ($tableColumns as $column): ?>
<th><input type="text" class="column-filter" placeholder="Filtern..."></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php $rowNumber = 1; ?>
<?php foreach ($tableData as $row): ?>
<tr>
<td><?= $rowNumber++; ?></td>
<?php foreach ($tableColumns as $column): ?>
<td><?= htmlspecialchars($row[$column] ?? '') ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div id="pagination-controls"></div>
<script>
document.addEventListener('DOMContentLoaded', function () {
const rowsPerPage = 250; // Anzahl der Zeilen pro Seite
const table = document.getElementById('data-table');
const tbody = table.querySelector('tbody');
const rows = Array.from(tbody.querySelectorAll('tr'));
const paginationControls = document.getElementById('pagination-controls');
let currentPage = 1;
let filteredRows = rows;
function renderTable() {
const start = (currentPage - 1) * rowsPerPage;
const end = start + rowsPerPage;
rows.forEach((row, index) => {
row.style.display = index >= start && index < end ? '' : 'none';
});
renderPaginationControls();
}
function renderPaginationControls() {
paginationControls.innerHTML = '';
const totalPages = Math.ceil(filteredRows.length / rowsPerPage);
for (let i = 1; i <= totalPages; i++) {
const button = document.createElement('button');
button.textContent = i;
button.classList.add('pagination-button');
if (i === currentPage) button.classList.add('active');
button.addEventListener('click', () => {
currentPage = i;
renderTable();
});
paginationControls.appendChild(button);
}
}
// Filterung
const filters = document.querySelectorAll('.column-filter');
filters.forEach((filter, index) => {
filter.addEventListener('input', function () {
const filterValue = this.value.toLowerCase();
filteredRows = rows.filter(row => {
const cell = row.cells[index + 1]; // +1 wegen der ID-Spalte
if (cell) {
const cellText = cell.textContent.toLowerCase();
return cellText.includes(filterValue);
}
return false;
});
currentPage = 1;
renderTable();
});
});
renderTable();
});
</script>
<style>
.pagination-button {
margin: 5px;
padding: 5px 10px;
cursor: pointer;
}
.pagination-button.active {
background-color: #007bff;
color: white;
border: none;
}
</style>
<?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 </option>
<option value="csv">csv</option>
<option value="backup_sql">Backup Table and Data</option>
</select>
<input type="password" name="admin_pass" placeholder="Admin Password"/>
<input type="text" name="exporttabelName" placeholder="Export Tablename" />
<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>