Created
September 22, 2018 12:01
-
-
Save ringate/8d2a2d99aeacda551d781c1d3939c26a to your computer and use it in GitHub Desktop.
Select data from mysql table as JSON format. (mysqli version)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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