task 2,3: XML->Json, SQL TAble -> JSON
This commit is contained in:
62
Zweites Jahr/json/fromSqlToJson.php
Normal file
62
Zweites Jahr/json/fromSqlToJson.php
Normal file
@@ -0,0 +1,62 @@
|
||||
<h1>SQL Table -> JSON</h1>
|
||||
<?php
|
||||
// Show Errors
|
||||
ini_set('display_errors', 1);
|
||||
ini_set('display_startup_errors', 1);
|
||||
error_reporting(E_ALL);
|
||||
|
||||
// config stuff
|
||||
$table = "Mitarbeiter";
|
||||
$dbname = "it-network";
|
||||
$host = "localhost";
|
||||
$jsonFileName = "dbdata.json";
|
||||
|
||||
// connect to db
|
||||
$pdo = new PDO("mysql:host=$host;dbname=$dbname", "phpmyadmin", "server");
|
||||
|
||||
// get data from db
|
||||
$dbData = $pdo->query("SELECT * FROM $table");
|
||||
|
||||
echo "<h2>SQL DATA</h2>";
|
||||
echo "<h3>Formatted</h3>";
|
||||
echo "Vorname | Nachname | Geburtsdatum | Gehalt | Geschlecht | Einstellungsdatum<br>";
|
||||
|
||||
$baseJson = [
|
||||
"Table" => $table,
|
||||
"Database" => $dbname,
|
||||
"Host" => $host,
|
||||
"Data" => []
|
||||
];
|
||||
|
||||
// append data to json and show it
|
||||
while ($row = $dbData->fetch()) {
|
||||
echo $row["m_vorname"]." | ".
|
||||
$row["m_nachname"]." | ".
|
||||
$row["m_geburtsdatum"]." | ".
|
||||
$row["m_gehalt"]." | ".
|
||||
$row["m_geschlecht"]." | ".
|
||||
$row["m_einstellung"]."<br>";
|
||||
|
||||
$baseJson["Data"][] = [
|
||||
"vorname" => $row["m_vorname"],
|
||||
"nachname" => $row["m_nachname"],
|
||||
"geburtsdatum" => $row["m_geburtsdatum"],
|
||||
"gehalt" => $row["m_gehalt"],
|
||||
"geschlecht" => $row["m_geschlecht"],
|
||||
"einstellung" => $row["m_einstellung"]
|
||||
];
|
||||
}
|
||||
|
||||
echo "<h2>JSON Array</h2>";
|
||||
// transfer php array into json
|
||||
$json = json_encode($baseJson, JSON_PRETTY_PRINT);
|
||||
echo "<pre>$json</pre>";
|
||||
|
||||
// safe file, show error or show written bytes
|
||||
$file = file_put_contents($jsonFileName, $json);
|
||||
if ($file === false) {
|
||||
echo "<br>Fehler beim Schreiben der Datei.";
|
||||
} else {
|
||||
echo "<br>dbdata.json geschrieben ($file Bytes).";
|
||||
}
|
||||
?>
|
||||
Reference in New Issue
Block a user