Convertir Tabla en JSON

PHP

Archivo 1 (PHP): Crea la tabla. Puedes usar esta:


$dbhost = 'localhost';
$dbuser = ''; // tu usuario de sql
$dbpass = ''; // tu password de sql
$dbname = ''; // tu base de datos
$newtable = 'example001'; /nombre de la nueva tabla

$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL to create the countries table
$createTableSQL = "
CREATE TABLE ".$newtable." (
    `Name` varchar(9),
    `Capital` varchar(10),
    `Continent` varchar(7)
)
";

if ($conn->query($createTableSQL) === TRUE) {
    echo "Table '".$newtable."' created successfully
"; // SQL to insert sample data $insertDataSQL = " INSERT INTO ".$newtable." (`Name`, `Capital`, `Continent`) VALUES ('Mexico', 'DF', 'America'), ('USA', 'Washington', 'America'), ('Spain', 'Madrid', 'Europe'), ('France', 'Paris', 'Europe'), ('Egypt', 'Cairo', 'Africa'), ('Portugal', 'Lisboa', 'Europe'), ('Eslovenia', 'Liubliana', 'Europe'), ('Letonia', 'Riga', 'Europe'), ('Italia', 'Roma', 'Europe'), ('Thailand', 'Bangkok', 'Asia'), ('Indonesia', 'Yakarta', 'Asia') "; if ($conn->query($insertDataSQL) === TRUE) { echo "Sample data inserted successfully"; } else { echo "Error inserting data: " . $conn->error; } } else { echo "Error creating table: " . $conn->error; } // Close connection $conn->close();
Archivo 2 (PHP, contiene HTML y JS): Convierte en JSON

<?php
$dbhost = 'localhost';
$dbuser = ''; // tu usuario de sql
$dbpass = ''; // tu password de sql
$dbname = ''; // tu base de datos
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

// prepara query
$query = "SELECT * FROM example_countries ORDER BY Name";
$result = mysqli_query($conn, $query);

$data = array();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}
$jsonData = json_encode($data);
?>
<table class="json"></table>

<script>
const ct = <?php echo $jsonData; ?>;
let list = document.querySelector(".json");

// For each DB row, create < option> with value
for (let i = 0; i < ct.length; i++) {
    let tr = document.createElement("tr")
    if (i === 0) {
        tr.innerHTML = "<td><b>Name</b></td><td><b>Capital</b></td>"
    } else {
    tr.innerHTML = "<td>" + ct[i].Name + "</td><td>" + ct[i].Capital + "</td>"
    }
    list.appendChild(tr);
}

</script>