Skip to content

Instantly share code, notes, and snippets.

@ringate
Created September 22, 2018 12:01
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/8d2a2d99aeacda551d781c1d3939c26a to your computer and use it in GitHub Desktop.
Save ringate/8d2a2d99aeacda551d781c1d3939c26a to your computer and use it in GitHub Desktop.
Select data from mysql table as JSON format. (mysqli version)
<?php
$host = 'localhost';
$username = 'dbuser';
$password = 'dbpass';
$db_name = 'dbname';
$table_name = 'tablename';
$db_conn = mysqli_connect($host, $username, $password) or die('Error: Could not connect.');
mysqli_select_db($db_conn, $db_name) or die('Error: Could not select database.');
$result = mysqli_query($db_conn, "SELECT * from " . $table_name) or die('Error: Could not query.');
$json = array();
if (mysqli_num_rows($result)) {
while ($row = mysqli_fetch_array($result, MYSQLI_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);
mysqli_close($db_conn);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment