Featured Post

Tablas Responsivas con Bootstrap 5 pc escritorio y dispositivos mobiles

Exporta tabla MYSQL a JSON CON PHP PDO Y JAVASCRIPT (FETCH)

                 


Codigo fuente del archivo index.php

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<style>
*{
margin: 0px;
padding-top: 10px;
box-sizing: border-box;
}
.container{
display:flex;
align-items:center;
justify-content:center;
}
#boton{
border:2px solid black;
background-color: white;
color:black;
padding:14px 28px;
font-size:16px;
cursor:pointer;
border-color:#DC143C;
border-radius:3px;
box-shadow:5px 5px 5px lightblue;
}
#boton:hover{
background-color: #DC143C;
color:white;
}
</style>
</head>
<body>
<div class="container">
<button id="boton" onclick="exporta_tabla();">EXPORTAR TABLA DE "MYSQL" A "JSON"</button>
</div>
<script>
function exporta_tabla(){
fetch('exporta.php', {
  method: "GET"
})
.then(response => {
swal("info!", "La Tabla se exporto con exito al formato JSON !!!", "success");
})
}
</script>
</body>
</html>

Codigo fuente del archivo exporta.php
<?php

$conexion=new PDO("mysql:dbname=tienda;host=localhost","root","root");

$conexion->query("SET NAMES 'UTF8'");

$consulta = $conexion->prepare('SELECT * FROM articulos');

$consulta->execute();

$vector_registros = [];

if (!$consulta){

echo 'Error al ejecutar';

}else{

while ($registros= $consulta->fetchAll(PDO::FETCH_ASSOC)){

      $vector_registros = $registros;

}

}

$fp = fopen('tabla_exportada.json', 'w');

fwrite($fp, json_encode($vector_registros));

fclose($fp);

?>


VISTA PREVIA


Comentarios