Change format JSON output in file? - php

I have the next PHP code that makes me a JSON file with data from my SQL table:
<?php
$mysqli = new mysqli('localhost','root','xxxx','xxxx');
$myArray = array();
$result = $mysqli->query("SELECT CONCAT(Datum , ' ', Tijd) as Datum, KleurL FROM metingen order by Datum ASC limit 20");
if ($result) {
$tempArray = array();
while ($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray,JSON_NUMERIC_CHECK);
$fp = fopen('resultsv2.json', 'w');
fwrite($fp, json_encode($myArray,JSON_NUMERIC_CHECK));
fclose($fp);
}
$result->close();
$mysqli->close();
?>
The ouput of the JSON file looks like this.:
[{"Datum":"17-01-2019 10:31:39","KleurL":17.68},{"Datum":"17-01-2019 11:10:59","KleurL":71.76},{"Datum":"18-01-2019 08:40:41","KleurL":70.7},{"Datum":"18-01-2019 10:30:01","KleurL":71.03},{"Datum":"18-01-2019 12:05:46","KleurL":70.56},{"Datum":"18-01-2019 14:31:58","KleurL":16.2}]
But I would like to see that the output of that file looks like this.:
[
[
17.68,
17-01-2019 10:31:39
],
[
18.11,
17-01-2019 11:15:20
]
]
How can I get this output in the JSON file?

The following code should achieve what you are trying to do. This code was tested on my pc and seems to be working perfectly.
<?php $mysqli = new mysqli('localhost', 'root', 'xxxx', 'xxxx');
if ($result = $mysqli->query("SELECT CONCAT(Datum , ' ', Tijd) as Datum, KleurL FROM metingen order by Datum ASC limit 20")) {
$current_row_number = 0;
$output = "[";
while ($row = $result->fetch_object()) {
if ($current_row_number > 0) {
$output = $output . ","; //add comma between each row
}
$output = $output . "[" . $row->KleurL . "," . $row->Datum . "]"; //add each row
$current_row_number++;
}
$output = $output . "]";
echo $output;
$fp = fopen('resultsv2.json', 'w');
fwrite($fp, $output);
fclose($fp);
}
$result->close();
$mysqli->close();
If you want to format the output nicely, use the following code:
<?php $mysqli = new mysqli('localhost', 'root', '244466666', 'tkd');
if ($result = $mysqli->query("SELECT CONCAT(Datum , ' ', Tijd) as Datum, KleurL FROM metingen order by Datum ASC limit 20")) {
$current_row_number = 0;
$output = "[";
while ($row = $result->fetch_object()) {
if ($current_row_number > 0) {
$output = $output . ","; //add comma between each row
}
$output = $output . "\n\t" . "[" . "\n\t\t" . $row->KleurL . "," . "\n\t\t" . $row->Datum . "\n\t" . "]"; //add each row
$current_row_number++;
}
$output = $output . "\n]";
// echo $output; //if you want to see the output in the terminal/command prompt
echo "<pre>" . $output . "</pre>"; //if you want to see the output in a browser
$fp = fopen('resultsv2.json', 'w');
fwrite($fp, $output);
fclose($fp);
}
$result->close();
$mysqli->close();

You can use the json_encode() JSON_PRETTY_PRINT options:
json_encode($myArray,JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
edit:
if you are using windows, you need to change the carriage return using something like this:
$myArray = array("test" => "data");
$buffer = json_encode($myArray,JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
echo str_replace("\n", "\r\n", $buffer);
// or
$fp = fopen('resultsv2.json', 'w');
fwrite($fp, str_replace("\n", "\r\n", $buffer));
fclose($fp);
If you are printing this into the browser you need to use <pre> tags
<pre>
echo json_encode($myArray,JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
</pre>

Related

sqlsrv_query returned false if I add condition to query string

I am getting data from sqlsrv_query() and pushing them into arrays and then add them into pg_query(with ARRAY ()). When I first ran query without conditions just SELECT it returned only 273 rows(should be 21225). Then I added a condition to ID to be more than 273 but then sqlsrv_query returned false. Please, Help...I can't solve it for about 2 weeks
<?php
//INCREASE MEMORY LIMIT TO STORE BIG AMOUNT OF DATA
ini_set('memory_limit', '1024*1024');
/////////////GET OBJECTS FROM MSSQL
$conInfo = array('UID' => 'test', 'PWD' => 'test', 'Database' => 'KTMOTIS' );
$serverName = "real address";//There is real IP-address instead
$connect = sqlsrv_connect($serverName, $conInfo);
$base_ids = array();
$otis_numbers = array();
$names = array();
$addresses = array();
$phones = array();
$unit_numbers = array();
$unittype_ids = array();
$is_protected = array();
$org_ids = array();
$old_ids = array();
$count = 0;
if ($connect) {
$tsql = "select Convert(INT, BASENUMBER) AS BASENUMBER, Convert(INT, OTISNUMBER) AS OTISNUMBER, ";
$tsql .= "Convert(VARCHAR(255), OBJECTNAME) AS OBJECTNAME, Convert(VARCHAR(255), INFO) AS INFO, ";
$tsql .= "Convert(VARCHAR(255), PHONES) AS PHONES, Convert(INT, UNITNUMBER) AS UNITNUMBER, ";
$tsql .= "Convert(INT, UNITTYPE) AS UNITTYPE, Convert(INT, ISPROTECTED) AS ISPROTECTED, ";
$tsql .= "Convert(INT, ORGID) AS ORGID, Convert(INT, CARDID) AS CARDID from CARDS; ";
//$tsql.= "WHERE Convert(INT, CARDID) > 1568 ;"
$stmt = sqlsrv_query($connect, $tsql);
echo "<br>";
if ($stmt === false) {
echo "<br>";
echo "Error in executing query.</br>".sqlsrv_errors();
die(print_r(sqlsrv_errors(), true));
}
else{
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC )) {
array_push($base_ids, $row["BASENUMBER"]);
array_push($otis_numbers, $row["OTISNUMBER"]);
$obj_name = $row["OBJECTNAME"];
$obj_name = str_replace('"', '', $obj_name);
$obj_name = str_replace(',', ' и ', $obj_name);
$count = $count + 1;
//echo 'OBJECT: '.$obj_name;
array_push($names, $obj_name);
$obj_info = $row["INFO"];
$obj_info = str_replace('"', '', $obj_info);
$obj_info = str_replace(',', ' и ', $obj_info);
array_push($addresses, $obj_info);
$obj_phone = $row["PHONES"];
$obj_phone = str_replace('"', '', $obj_phone);
$obj_phone = str_replace(',', ' и ', $obj_phone);
array_push($phones, $obj_phone);
array_push($unit_numbers, $row["UNITNUMBER"]);
array_push($unittype_ids, $row["UNITTYPE"]);
array_push($is_protected, $row["ISPROTECTED"]);
array_push($org_ids, $row["ORGID"]);
array_push($old_ids, $row["CARDID"]);
}
echo "<br>";
echo "COUNT: ".$count;
/*Convert AS JSON*/
$base_ids = json_encode($base_ids, JSON_UNESCAPED_UNICODE);
$otis_numbers = json_encode($otis_numbers, JSON_UNESCAPED_UNICODE);
$names = json_encode($names, JSON_UNESCAPED_UNICODE);
$addresses = json_encode($addresses, JSON_UNESCAPED_UNICODE);
$phones = json_encode($phones, JSON_UNESCAPED_UNICODE);
$unit_numbers = json_encode($unit_numbers, JSON_UNESCAPED_UNICODE);
$unittype_ids = json_encode($unittype_ids, JSON_UNESCAPED_UNICODE);
$is_protected = json_encode($is_protected, JSON_UNESCAPED_UNICODE);
$org_ids = json_encode($org_ids, JSON_UNESCAPED_UNICODE);
$old_ids = json_encode($old_ids, JSON_UNESCAPED_UNICODE);
/*INSERT OR UPDATE OBJECTS IN POSTGRESQL*/
$con = pg_connect("host=real IP port=5432 dbname=technics user=postgres password=1234") or die('Could not connect: ' . pg_last_error());
$query = "SELECT * FROM techpart.update_objects(ARRAY " . $base_ids . ", ARRAY " . $otis_numbers . ", ARRAY " . $names . ", ARRAY " . $addresses . ", ARRAY " . $phones . ", ARRAY " . $unit_numbers . ", ARRAY " . $unittype_ids . ", ARRAY " . $is_protected . ", ARRAY " . $org_ids . ", ARRAY " . $old_ids . ");";
$query = str_replace('"', "'", $query);
$query = str_replace("L'A", "LA", $query);
//echo $query;
echo "<br>";
if (sizeof($old_ids) > 0) {
echo "ROW: ". var_dump($row);
$rs = pg_query($con, $query) or die("Cannot execute query: $query\n");
$row = pg_fetch_row($rs);
if ($row[0] == true) {
echo "Right!";
}
else{
echo "Wrong!";
}
}
else{
echo "Empty!";
}
pg_close();
}
}
else {
echo "Connection not established.\n";
die( print_r(sqlsrv_errors(), true));
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($connect);
?>
I've searched about limitations of PHP array(there is no limit) and string. Then I added the line:
ini_set('memory_limit', '1024*1024');
Executed sqlsrv_query() with parameter. Still doesn't work. It didn't even iterate through $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC ){}
WHAT IT RETURNS:
bool(false) ROW:
Warning: pg_query(): Query failed: ERROR: cannot determine type of empty array LINE 1: SELECT * FROM techpart.update_objects(ARRAY [], ARRAY [], AR... ^ HINT: Explicitly cast to the desired type, for example ARRAY[]::integer[]. in /var/www/position/test/upload_main_mssql_data.php on line 84
Cannot execute query: SELECT * FROM techpart.update_objects(ARRAY [], ARRAY [], ARRAY [], ARRAY [], ARRAY [], ARRAY [], ARRAY [], ARRAY [], ARRAY [], ARRAY []);

Importing text file into MySQL php program

I have a code that I took from https://www.howtoforge.com/community/threads/importing-text-file-into-mysql.7925/ and changed to what I needed it for but when I run the program it doesn't import the data into the database
Text file
GeoID|X|Y|Wood|Clay|Iron|Stone|Food|TerrainSpecificTypeID|TerrainCombatTypeID|RegionID
7025277|279|-1321|0|0|0|0|0|62|14|31
7025278|279|-1320|0|0|0|0|0|62|14|31
7025279|279|-1319|0|0|0|0|0|62|14|31
7025280|279|-1318|0|0|0|0|0|62|14|31
7025281|279|-1317|0|0|0|0|0|62|14|31
7025282|279|-1316|0|0|0|0|0|62|14|31
7025283|279|-1315|0|0|0|0|0|62|14|31
7025284|279|-1314|0|0|0|0|0|62|14|31
7025285|279|-1313|0|0|0|0|0|62|14|31
7025286|279|-1312|0|0|0|0|0|62|14|31
PHP code that i am currently using
<?php
// Set Mysql Variables
$username = "root";
$auth = 'i-have-removed-it';
$db = mysql_connect("localhost", $username, $auth);
mysql_select_db("testdb",$db);
$file = "/tmp/map_datafile_test.txtt";
$fp = fopen($file, "r");
$data = fread($fp, filesize($file));
fclose($fp);
$output = str_replace("\t|\t", "|", $data);
$output = explode("\n", $output);
$language_id = "1";
$categories_id = 0;
foreach($output as $var) {
$categories_id = $categories_id + 1;
$tmp = explode("|", $var);
$GeoID = $tmp[0];
$X = $tmp[1];
$Y = $tmp[2];
$Wood = $tmp[3];
$Clay = $tmp[4];
$Iron = $tmp[5];
$Stone = $tmp[6];
$Food = $tmp[7];
$TerrainSpecificTypeID = $tmp[8];
$TerrainCombatTypeID = $tmp[9];
$RegionID = $tmp[10];
echo " categories_id: " . $categories_id . " Artikelgroep: " . $Artikelgroep . "<br>";
$sql = "INSERT INTO `World_Map`(`GeoID`, `X`, `Y`, `Wood`, `Clay`, `Iron`, `Stone`, `Food`, `TerrainSpecificTypeID`, `TerrainCombatTypeID`, `RegionID`) VALUES ('$GeoID','$X','$Y','$Wood','$Clay','$Iron','$Stone','$Food','$TerrainSpecificTypeID ','$TerrainCombatTypeID ','$RegionID')" or die("Insert failed: " . mysql_error());
mysql_query($sql);
}
echo "Done!";
?>
You need to set the variables $GeoID, $X, $Y, $Wood, $Clay, ...
In the foreach loop you get each line of the file, and in $tmp you get each column. So $GeoID should be $tmp[0], $X should be $tmp[1] and so on.

Generate JSON From Mysql Using PHP

i have little problem here, i want to generate some data to specific JSON format from Mysql using PHP, this is my PHP code
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
// echo(json_encode($names));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
?>
With this code, the result was
[
[1478616679000, 1478616677000, 1478616675000, 1478616673000, 1478616671000],
[28.4126, 28.5361, 28.4126, 28.4126, 28.2891]
]
Yes, that is valid JSON but, i want to use this JSON for chart in highcharts.com, so i need the JSON format like this
[
[1257811200000, 29.00],
[1257897600000, 29.04],
[1257984000000, 28.86],
[1258070400000, 29.21],
[1258329600000, 29.52],
[1258416000000, 29.57],
[1258502400000, 29.42],
[1258588800000, 28.64],
[1258675200000, 28.56],
[1258934400000, 29.41],
[1259020800000, 29.21],
[1259107200000, 29.17],
[1259280000000, 28.66],
[1259539200000, 28.56]
]
Gladly if someone can help me, i'm stuck for a days try to solving this issue
If you want the code like that, you must fix the code:
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
must be something like this:
while($row = $result->fetch_array()){
$rows[] = array(
(float)$row['ai0_hist_value'],
strtotime($row['meas_date'])*1000);
}
echo (json_encode($rows));
You were saving in $data2 an array with two arrays, the text and the data. You must save a row for each pair of 'text' and 'data'.
Could construct the formatted series data to begin with like below:
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$seriesData[] = [ strtotime($row['meas_date'])*1000, (float)$row['ai0_hist_value'] ];
}
echo (json_encode($seriesData));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
This will generate the array you want, there is no need to do all that fiddling with the data from the database
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
$rows = array();
if ($result = $db->query($sql)) {
while($row = $result->fetch_array()){
$rows[] = array(strtotime($row['meas_date'])*1000,
$row['ai0_hist_value']
);
}
}
echo json_encode($rows);
Now you will need to convert the text to float in the javascript. This is because JSON is passed as text and not any other data type, so it has to be converted, if necessary in the receiving javascript.

Check and set array to null

I am trying to set result_array to null if there are no existing data in the database. The result should be shown in a table format but I cannot get the result_array as null and keep getting error on the line $result_array[] = null;
global $db;
$db = new mysqli();
$db->connect("localhost", "root", "", "databasename");
$db->set_charset("utf8");
if ($db->connect_errno) {
printf("Connection has failed: %s\n", $db->connect_error);
exit();
}
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="url">';
$html .= '<h3>name</h3>';
$html .= '</a>';
$html .= '</li>';
$search = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search = $db->real_escape_string($search);
if (strlen($search) >= 1 && $search !== ' ') {
$query = 'SELECT * FROM tablename WHERE name LIKE "%'.$search.'%"';
$result = $db->query($query) or trigger_error($db->error."[$query]");
if(!$results = $result->fetch_array()){
$resultArray[] = null;
}
else{
while($results = $result->fetch_array()) {
$resultArray[] = $results;
}
}
if (isset($resultArray)) {
foreach ($resultArray as $result) {
$show_name = preg_replace("/".$search."/i", "<b class='highlight'>".$search."</b>", $result['name']);
$show_url = 'index.php';
$out = str_replace('name', $show_name, $html);
$out = str_replace('url', $show_url, $out);
$_SESSION['result']= $result['name'];
echo($out);
}
}else{
$out = str_replace('url', 'javascript:void(0);', $html);
$out = str_replace('name', '<b>No Results.</b>', $out);
echo($out);
}
}
?>
why aren't you using this?
...
$result_array = array();
if(!$results = $result->fetch_array()){
//do nothing
}
else{
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
...
Also please use either $result_array or $resultArray

How do I echo out something different when reached last row?

I am wanting to not echo out the comma at the end of the echo after the last row. How can I do that? Here is my code:
<?php
header("Content-type: application/json");
echo '{"points":[';
mysql_connect("localhost", "user", "password");
mysql_select_db("database");
$q = "SELECT venues.id, venues.lat, venues.lon, heat_indexes.temperature FROM venues, heat_indexes WHERE venues.id = heat_indexes.venue_id";
$res = mysql_query($q) or die(mysql_error());
while ($point = mysql_fetch_assoc($res)) {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'] . ",";
}
mysql_free_result($res);
echo ']}';
?>
Could you not use json_encode() instead, rather than hand-crafting the JSON?
$result = array();
//snip
while ($point = mysql_fetch_assoc($res)) {
$result[] = $point['lat'];
$result[] = $point['lon'];
$result[] = $point['temperature'];
}
//snip
header("Content-type: application/json");
echo json_encode( array('points' => $result) );
Use a count query to get the number of rows to begin with.
$query= "SELECT COUNT(*) FROM venues";
$count= mysql_query($q);
Then introduce a conditional and a count decrease each time through...
while ($point = mysql_fetch_assoc($res)) {
$count = $count - 1;
if ($count == 1) {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'];
} else {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'] . ",";
}
Json encode would probably be your best bet, but you could also use trim();
Rather than echoing in the while loop, append to a variable. Once outside the while loop, use $output = trim($output, ',') to remove trailing commas.
About the comma problem, I always target the first item instead of the last:
$first = true;
while ($point = mysql_fetch_assoc($res)) {
if ($first)
{
$first = false;
}
else
{
echo ",";
}
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'];
}
You can use mysql_num_rows() to find out how many rows are in the result set passed back from your last query.
...
$res = mysql_query($q) or die(mysql_error());
$num_rows = mysql_num_rows($res);
Then combine that with Scotts answer and you should be set.

Categories