Error of php script while encoding to json - php

I have currently a php script as given below:
<?php
$con=mysqli_connect("localhost","username","password","temp");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = mysqli_real_escape_string($con, $_POST['username']);
$result = mysqli_query($con,"SELECT imagename FROM table3 where username='$username'");
$rows = array();
while($r = mysqli_fetch_assoc($result))
{
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($con);
?>
The output which I get after running this script is in the form given below:
[{"imagename":"1"},{"imagename":"2"}]
But I need a string in a format like this as my output:
{"Android":[{"imagename":"1"},{"imagename":"2"}]}.
That is, I should be able to add the string {"Android": to the beginning of my actual output and add the string } to the ending part of my actual output.
So what code should I need to add extra to obtain like the above format. Can someone please help me out.. Thanks in advance..

try this by defining your key in the array of $rows you should get your result you want.
{
$rows['Android'] = $r;
}

Related

JSON encodes cyryllic as a null

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'];

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;
?>

First value of my PHP Array is returned as 'null' when it has a value

I'd really like some help with the following MySQL / PHP problem (maybe bug?)
I'm trying to retrieve and display an array of data from my database using MySQL / PHP, but when I echo out the array, it returns the first value as 'null'.
So, even though the database has the following info:
"Example 1", "Example 2", "Example 3"...
The php echos out:
"null", "Example 2, "Example 3"
I would imagine this would be a common problem, but I haven't managed to find the required information elsewhere on the internet, so I'm hoping you kind folks can help.
My PHP
/* If connection to database, run sql statement. */
if ($conn) {
$fetch = mysql_query("SELECT column FROM table WHERE approved = '1' ");
// declare empty array to fill later
$result = array();
// make sure the MySQL pointer is looking at the first row
mysql_data_seek($fetch, 0);
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
foreach ($row as $value) {
$row_array = $value;
// push info into new array with just the value
array_push($result, $row_array);
}
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($result);
UPDATE
New code courtesy of Mark B:
if ($conn)
{
$sql = "SELECT column_name FROM table WHERE comment_approved = '1' ";
$query = mysql_query($sql) or die(mysql_error());
$result = array();
while ($row = mysql_fetch_assoc($query)) {
$result[] = $row['column_name'];
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($result);
NOTE:
The 'null' problem still occurs with or without the:
mysql_data_seek($fetch, 0);
as that appears to do nothing.
Any help would be great!
SOLVED
Thanks to Mark B who pointed out that the problem was probably in the database rather than the PHP, it turned out there was the character ` lurking where there should have been a '. This caused the information to appear 'null'.
$sql = "SELECT column FROM table WHERE approved = '1'";
$result = mysql_query($sql) or die(mysql_error());
$data = array();
while($row = mysql_fetch_assoc($result)) {
$data[] = $row['column'];
}
echo json_encode($data);
You shouldn't have to do the seek, as you've not done anything with the result at the time. And since you're only fetching a single column from the database, there's no need for the inner foreach() loop either.
Try removing the call to mysql_data_seek. I see no reason why the MySQL pointer wouldn't already point to the first row at the first call to mysql_fetch_array.
You could try removing mysql_data_seek($fetch, 0); as the pointer will already be on the first record if you have just made the query.

Display mysql data in php function

Ok i got a problem now i want to display a data from the database and display it through a function now how do i do that??
like i have fetched a row from the database and its name is $row_field['data']; and it is correct now i have assigned a variable to it like this $data = $row_field['data']; now if i call it in a function it shows undefined variable even after i assigned it global in the function like this
function fun(){
global $data;
echo $data;
}
but if i assign it a value like 1 or 2 or anything it gets displayed without any error why is that so??
If it displays if you assign it a value like 1 or 2 while still in the global scope, then I can only assume that your database did not return the result you thought it did. Does the database value display if you echo it out outside of the function?
Global is evil. I dont know what you are trying to do, but why dont you just do the query in the function itself?
If you have a column named data and your php call was something like
$result = mysql_query("SELECT data FROM mytable");
while ($row_field = mysql_fetch_assoc($result, MYSQL_NUM)) {
...
}
Then you could replace ... with print $row_field['data'].
Else please provide a snippet of your code where you query the db and retrieve the result.
When learning php try to start with simple things. For example in order to get some data from a database follow the examples from php website.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
If all this goes well go a little further change a little the while loop.
$myArray = array();
while ($row = mysql_fetch_assoc($result)) {
$myArray[] = $row;
}
mysql_free_result($result);
// now you can start playing with your data
echo $myArray[0];
Small steps...

Categories