1

Hello I am trying to output my mysqli database to a js file after encoding it, I have no trouble encoding it with json_encode but how can I get it into a js file (updating every time the mysqli data is updated)

$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM tablename")) {
    $tempArray = array();
    while($row = $result->fetch_object()) {
            $tempArray = $row;
             array_push($myArray, $tempArray);
         }
     echo json_encode($myArray);
 }

$result->close();
$mysqli->close();

Any help or insight would be great! thanks

Benjamin
  • 657
  • 2
  • 10
  • 31

1 Answers1

1

To return a json file you will have to set json headers at the top of your PHP code:

header('Content-Type: application/json');

If you just want to write the json code into an external file you would have to use PHPs fwrite().

However you can't automatically update the file, when the database is updated. You need to call your PHP file in order to update the json file.

Maybe you can solve this by using a MySQL trigger in your database, more information here.

Community
  • 1
  • 1