JSON encodes cyryllic as a null - php

I have MYSQL table with Cyrillic symbols.
This is my MYSQL table
And i use PHP to get MYSQL result and encode it to JSON.
<?php
include 'connection.php';
$array_to_json = array();
$query = "SELECT * FROM online";
$result = mysqli_query($link, $query);
mysqli_set_charset("utf8");
while($row = $result->fetch_assoc()) {
$row_array['parameters'] = $row['parameters'];
$row_array['Descriptions'] = $row['Descriptions'];
$row_array['units'] = $row['units'];
array_push($array_to_json, $row_array);
}
echo json_encode($array_to_json, JSON_UNESCAPED_UNICODE);
$result->close();
?>
And as a result i have got null.
JSON returns null
What do i do wrong?

Did you try using
$row_array['parameters'] = base64_encode($row['parameters']);
$row_array['Descriptions'] = base64_encode($row['Descriptions']);
$row_array['units'] = base64_encode($row['units']);
array_push($array_to_json, $row_array);

recheck your table structure and ensure that there is no extra blank space
for instance:
$row['Descriptions ']
instead of:
$row['Descriptions'];

Related

put comma in numbers on json array using php

i want to put comma's in numbers
The output is this which is encoded in json array
[{"total2":"7619627.0000"}]
I want to change the number in this format
[{"total2":"7,619,627"}]
heres the php code
$sql2 = "SELECT SUM(NettoPrice) AS total2 FROM Sales WHERE OrderType = 8";
$result2 = $conn->query($sql2);
// output data of each row
while($row[] = $result2->fetch_assoc()) {
$json = json_encode($row);
}
echo $json;
$conn->close();
?>
With MYSQL 5.5:
SELECT FORMAT(SUM(NettoPrice),0) AS total2;
SQL fiddle
With PHP
number_format('7619627.0000',0);
Use number_format();
$row[count($row)-1]['total2'] = number_format($row[count($row)-1]['total2']);
$json = json_encode($row);

Running two select queries in php and encoding it in json format?

I have two tables billing_all and payment_details. I am trying to write php code such that I can run the 2 queries in the same php code and encode their data in json format.I am currently using the following code to achieve that without json encode :-
<?php
include "config.php";
$dbname ="webappdb";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$dbname);
if(!$con)
{
echo "Connection Error".mysqli_connect_error();
}
else{
//echo "";
}
$sql = "SELECT SUM(total_wt) FROM `billing_all` WHERE date ='15-Apr-2016';";
$sql .= "SELECT pymt_amount, mode_of_pymt FROM `payment_details` WHERE DATE ='15-Apr-2016';";
// Execute multi query
if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set
if ($result=mysqli_store_result($con)) {
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
printf("%s%s\n",$row[0],$row[1]);
}
// Free result set
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}
mysqli_close($con);
?>
How can I encode the received data in json format? I tried something like:-
// Store first result set
if ($result=mysqli_store_result($con))
{
$r = array();
while($row = mysqli_fetch_array($result))
{
array_push($r,
array('total_wt'=>$row[0],
'pymt_amount'=>$row[0],$row[1],
'mode_of_pymt'=>$row[0],$row[1]));
}
echo json_encode(array("result"=>$r));
Which does not give me the expected result.How can I encode the data
in the right way? The following is the structure for the 2 tables
I am new to programming any help is appreciated.Thank you?
<?php
//Joining both tables on the basis of doc_no column
$sql = "SELECT billing_all.SUM(total_wt) AS total
,payment_details.pymt_amount
,payment_details.mode_of_pymt
FROM billing_all
,payment_details
WHERE billing_all.doc_no = payment_details.doc_no
AND billing_all.DATE = '15-Apr-2016'";
// Executing query
$res = mysqli_query($con,$sql);
//initializing array to store result
$rows = array();
//Iterating result and storing each row in $r then array $rows to covert result set into array because json accept array as parameter.
while($r = mysqli_fetch_assoc($res))
{
$rows[] = $r;
}
//print whole array in json format
echo json_encode($rows); ?>

how i can use JSON result in calculation in php

i want to use json result in some calculation but whatever i try it didn't work.
<?php
//product id
$gp_id=$_GET['gp_id'];
//Importing the database connection
require_once('dbConnect.php');
$sql2 = "SELECT sum(rating_score) AS total_rate ,count(consumer_id) AS consumer
FROM productrate
WHERE gp_id='$gp_id'";
//Getting result
$result = mysql_query($sql2);
//Adding results to an array
$res = array();
while($row = mysql_fetch_array($result))
{
array_push($res, array(
// "gp_id"=>$row['gp_id'],
"total_rate"=>$row['total_rate'],
"consumer"=>$row['consumer']
)
); }
//Displaying the array in json format
$objJson=json_encode($res);
echo $objJson;
//calculate avg rate of specific product
$avg_rate = (int)"total_rate" / (int)"consumer";
echo $avg_rate ;
?>
as you see at the end i try to do some calculation but it didn't work.
this is the output...
[{"total_rate":"18","consumer":"4"}]
Warning: Division by zero in C:\xampp\htdocs\totalrate\highRate.php on line 33
$objJson=json_encode($res); makes json string. For example '{"a":1,"b":2,"c":3,"d":4,"e":5}'. You cannot use it like variables. Its string.
$avg_rate = "total_rate" / "consumer";
Looks like you trying to divide a string with another string.
Try using the array element instead, like:
$avg_rate = $res["total_rate"] / $res["consumer"];
finally i solve the problem ...
//product id
$gp_id=$_GET['gp_id'];
//Importing the database connection
require_once('dbConnect.php');
$sql2 = "SELECT sum(rating_score) AS total_rate ,count(consumer_id) AS consumer
FROM productrate
WHERE gp_id='$gp_id'";
//Getting result
$result = mysql_query($sql2) or die(mysql_error());
//Adding results to an array
$res = array();
while($row = mysql_fetch_array($result))
{
array_push($res, array(
"avg_rate"=>$row['total_rate']/ $row['consumer'],
"total_rate"=>$row['total_rate'],
"consumer"=>$row['consumer']
)
); }
//Displaying the array in json format
$objJson=json_encode($res);
echo $objJson;
?>

jsonobjects sudently return empty

I was able before to receive json array, now I am receiving empty like this
{"result":[]} this is the url
this is the php code
$con=mysqli_connect($host,$uname,$pwd,$db);
$sql = "select ID,NAME, URL from OBJECTS";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('ID'=>$row[0],
'NAME'=>$row[1],
'URL'=>$row[2]
));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
this is my database
NAME is a reserved keyword in MYSQL, I bet you shall change the column name to something like objects_name, then you fetch the query properly. Or you can quote the columns, like :
$sql = "select `ID`,`NAME`, `URL` from `OBJECTS`";
It seems what mysqli_fetch_array($res)) returns empty result.
You can check this: add echo into cycle:
while($row = mysqli_fetch_array($res)) {
print_r($row);
array_push($result,
array(
'ID'=>$row[0],
'NAME'=>$row[1],
'URL'=>$row[2]
));
}
Check also connect with database. Add these two lines before connect to show errors
error_reporting(E_ALL);
ini_set('display_errors', 1);

Mysql fetch all rows and echo as json

I've got a database with 5 columns and multiple rows. I want to fetch the first 3 rows and echo them as an array. So far I can only get the first row (I'm new to PHP and mysql). Here's my PHP so far:
//==== FETCH DATA
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_row($result);
//==== ECHO AS JSON
echo json_encode($array);
Help would be much appreciated.
You need to loop through the results. mysql_fetch_row gets them one at a time.
http://php.net/manual/en/function.mysql-fetch-row.php
The code would end up like:
$jsonData = array();
while ($array = mysql_fetch_row($result)) {
$jsonData[] = $array;
}
echo json_encode($jsonData);
//json_encode()
PLEASE NOTE
The mysql extension is deprecated in PHP 5.5, as stated in the comments you should use mysqli or PDO. You would just substitute mysqli_fetch_row in the code above.
http://www.php.net/manual/en/mysqli-result.fetch-row.php
I do like this while quering an ODBC database connection with PHP 5.5.7, the results will be in JSON format:
$conn = odbc_connect($odbc_name, 'user', 'pass');
$result = odbc_exec($conn, $sql_query);
Fetching results allowing edit on fields:
while( $row = odbc_fetch_array($result) ) {
$json['field_1'] = $row['field_1'];
$json['field_2'] = $row['field_2'];
$json['field_3'] = $row['field_1'] + $row['field_2'];
array_push($response, $json);
}
Or if i do not want to change anything i could simplify like this:
while ($array = odbc_fetch_array($result)) { $response[] = $array; }
What if i want to return the results in JSON format?, easy:
echo json_encode($response, true);
You can change odbc_fetch_array for mysqli_fetch_array to query a MySql db.
According to the PHP Documentation mysql_fetch_row (besides that it's deprecated and you should use mysqli or PDO)
Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.
so you need for example a while loop to fetch all rows:
$rows = array();
while ($row = mysql_fetch_row($result)) {
$rows[] = $row;
}
echo json_encode($rows);
I leave it to you how to only fetch 3 rows :)
You need to put this in some kind of a loop, mysql_fetch_row returns results one at a time.
See example:
http://www.php.net/manual/en/mysqli-result.fetch-row.php#example-1794
$result = mysql_query( "SELECT * FROM $tableName ORDER BY id LIMIT 3");
$json = array();
while($array = mysql_fetch_row($result)){
$json[] = $array;
}
echo json_encode($json);

Categories