Skip to content

Instantly share code, notes, and snippets.

@locvfx
Created August 5, 2018 17:41
Show Gist options
  • Save locvfx/6441bae26a2f8169042f32764bbc971d to your computer and use it in GitHub Desktop.
Save locvfx/6441bae26a2f8169042f32764bbc971d to your computer and use it in GitHub Desktop.
How to convert MYSQL data to JSON using PHP
<?php
// Initialize variable for database credentials
$dbhost = 'hostname';
$dbuser = 'username';
$dbpass = 'password';
$dbname = 'sakila';
//Create database connection
$dblink = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
//Check connection was successful
if ($dblink->connect_errno) {
printf("Failed to connect to database");
exit();
}
//Fetch 3 rows from actor table
$result = $dblink->query("SELECT * FROM actor LIMIT 3");
//Initialize array variable
$dbdata = array();
//Fetch into associative array
while ( $row = $result->fetch_assoc()) {
$dbdata[]=$row;
}
//Print array in JSON format
echo json_encode($dbdata);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment