Mysql to JSON using php


Php script to fetch tables from Mysql database and output the results to a JSON file.

DB.php

<?php

  $host = "myhost";
  $user = "myuser";
  $pass = "mypassword";

  $databaseName = "mydatabase";
  $tableName = "mytable";

?>

fetch.php

<?php

  include 'DB.php';

  // connect
  $mysqli = new mysqli($host,$user,$pass,$databaseName);
  $result = $mysqli -> query("SELECT column1, column2 FROM $tableName");
  
  while ($row = $result -> fetch_assoc()) {
    $data[] = $row;
  }

  // write to json file
  $fp = fopen('myfile.json', 'w');
  fwrite($fp, json_encode($data));
  fclose($fp);

  $mysqli -> close();

?>