Muestra del código PHP ejercicio 7
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>CFGS - Desarrollo de Aplicaciones Web</title>
<style>
body {
font-family: Arial, sans-serif;
background: #f4f6f9;
margin: 0;
padding: 0;
}
header {
background: #F59C27;
color: white;
padding: 15px;
text-align: center;
}
h1 {
margin: 0;
}
main {
max-width: 1200px;
margin: 30px auto;
padding: 20px;
background: white;
border-radius: 10px;
box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}
ul {
list-style: none;
padding: 0;
}
footer{
margin: auto;
background-color: #F59C27;
text-align: center;
height: 150px;
color: white;
position: fixed;
bottom: 0;
left: 0;
width: 100%;
}
a{
text-decoration: none;
color:purple;
}
table{
border: 0;
}
td{
padding: 10px;
border-width: 4px;
}
#encabezado{
background-color: lightsteelblue;
font-weight: bold;
}
.codigos{
background-color: lightblue;
}
.mostrar{
background-color: lightsalmon;
}
tr{
height: 80px;
}
input{
border-radius: 5px;
}
#boton{
border-radius: 5px;
width: 150px;
background-color: lightgreen;
}
label{
font-weight: bold;
}
h3{
text-decoration: underline;
}
#formulario table{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<header>
<h1><b>UT4: TÉCNICAS DE ACCESO A DATOS EN PHP</b></h1>
<h4><a href="../../AMNDWESProyectoDWES/indexProyectoDWES.php">Alberto Méndez Núñez | 03/10/2025</a></h4>
<p>Curso 2025/2026 - Grupo DAW2</p>
</header>
<main>
<h2><b>Ejercicio 7</b></h2>
<?php
/*
* Autor: Alberto Méndez Núñez
* Fecha de última modificación: 09/12/2025
* Importación de departamentos desde fichero JSON.
*/
require_once '../config/confDBPDO.php';
try {
$miDB = new PDO(RUTA, USUARIO, PASS);
$miDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $ex) {
die("<h3>Error de conexión: {$ex->getMessage()}</h3><p>Código: {$ex->getCode()}</p>");
}
/* ==================== Leer fichero JSON ==================== */
$jsonFile = "../tmp/departamentos.json";
if (!file_exists($jsonFile)) {
die("<h3>Error: El fichero JSON no existe en /tmp.</h3>");
}
$jsonData = file_get_contents($jsonFile);
$aDepartamentos = json_decode($jsonData, true);
if ($aDepartamentos === null) {
die("<h3>Error al decodificar JSON: " . json_last_error_msg() . "</h3>");
}
/* ==================== Insertar datos ==================== */
try {
$miDB->beginTransaction();
$sql = "INSERT INTO T02_Departamento
(T02_CodDepartamento, T02_DescDepartamento,
T02_FechaCreacionDepartamento, T02_VolumenNegocio, T02_FechaBajaDepartamento)
VALUES
(:cod, :desc, NOW(), :vol, NULL)";
$stmt = $miDB->prepare($sql);
foreach ($aDepartamentos as $departamento) {
// Validación básica
if (empty($departamento['T02_CodDepartamento']) || empty($departamento['T02_DescDepartamento'])) {
throw new Exception("Faltan datos obligatorios en el JSON para un departamento.");
}
$stmt->execute([
':cod' => $departamento['T02_CodDepartamento'],
':desc' => $departamento['T02_DescDepartamento'],
':vol' => $departamento['T02_VolumenNegocio'] ?? 0
]);
}
$miDB->commit();
echo "<h2>Departamentos importados correctamente.</h2>";
/* ==================== Mostrar los datos insertados ==================== */
echo "<h3>Departamentos importados:</h3>";
echo "<table border='1' cellpadding='6' cellspacing='0'>
<tr>
<th>Código</th>
<th>Descripción</th>
<th>Volumen</th>
</tr>";
foreach ($aDepartamentos as $dep) {
echo "<tr>
<td>{$dep['T02_CodDepartamento']}</td>
<td>{$dep['T02_DescDepartamento']}</td>
<td>{$dep['T02_VolumenNegocio']}</td>
</tr>";
}
echo "</table>";
} catch (Exception $ex) {
$miDB->rollBack();
echo "<h3>Error en la importación:</h3>";
echo "<p><strong>Mensaje:</strong> {$ex->getMessage()}</p>";
if ($ex instanceof PDOException) {
echo "<p><strong>Código PDO:</strong> {$ex->getCode()}</p>";
}
} finally {
unset($miDB);
}
?>
</main>
</body>
</html>