Skip to content

Instantly share code, notes, and snippets.

@ringate
Created September 22, 2018 12:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ringate/e98a4e0ebf75b3fc5c4de21eda344e8e to your computer and use it in GitHub Desktop.
Save ringate/e98a4e0ebf75b3fc5c4de21eda344e8e to your computer and use it in GitHub Desktop.
Select data from mysql table as JSON format.
<?php
$host = 'localhost';
$username = 'dbuser';
$password = 'dbpass';
$db_name = 'dbname';
$table_name = 'tablename';
$db_conn = mysql_connect($host, $username, $password) or die('Error: Could not connect.');
mysql_select_db($db_conn, $db_name) or die('Error: Could not select database.');
$result = mysql_query($db_conn, "SELECT * from " . $table_name) or die('Error: Could not query.');
$json = array();
if (mysql_num_rows($result)) {
while ($row = mysql_fetch_array($result, mysql_ASSOC)) {
$json['rawData'][] = $row;
}
}
// for debug
//echo json_encode($json, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
// for production
echo json_encode($json, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
mysql_close($db_conn);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment