Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save PortionLK/be929d432ceab5685ae0e2040ad77028 to your computer and use it in GitHub Desktop.

Select an option

Save PortionLK/be929d432ceab5685ae0e2040ad77028 to your computer and use it in GitHub Desktop.
output data as json in php
<?php
$host = "localhost"; //Your database host server
$db = "..."; //Your database name
$user = "..."; //Your database user
$pass = "..."; //Your password
$connection = mysql_connect($host, $user, $pass);
if(!$connection){
die("Database server connection failed.");
}else{
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if(!$dbconnect){
die("Unable to connect to the specified database!");
}else{
$query = "SELECT * FROM movies";
$resultset = mysql_query($query, $connection);
$records = array();
$response = array(); //extra
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
$json = json_encode($records);
header("content-type:application/json");
echo $json;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment