I'm working on implementing a chart from highcharts. The data needed in order for it to be displayed needs to be in the .json format.
It has the following scheme:
[
[
1167609600000,
21
]
]
I'm getting my data from a mysql database via a php script:
<?php
//OPEN CONNECTION TO DB
$connection = mysqli_connect('localhost','abc','def','ghi') or die("Error " . mysqli_error($connection));
//SELECT ROWS NEEDED
$sql = "SELECT test, temp FROM database";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//CONVERT MYSQL TO PHP ARR
$json_array= array();
while ($row= mysqli_fetch_assoc($result))
{
$json_array[]= $row;
}
//WRITE DATA TO FILE
$fp = fopen('temps.json', 'w');
fwrite($fp, json_encode($json_array, JSON_PRETTY_PRINT));
fclose($fp);
//DISCONNECT FROM DB
mysqli_close($connection);
?>
Now comes my problem. The data generated by my script looks like this:
[
{
"a": "2",
"price": "15"
}
]
Firstly, I dont know how to supress the column-name of every result in my sql query. Secondly, I dont get why my script creates curly brackets instead of square ones. And thirdly, why does it use "." for every value.
Anybody able to help me out?
Thank you
You push in your array an associative array, so the key are kept and are displayed in your JSON:
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = [ (int)$row['a'], (int)$row['price'] ];
}
Will outputs:
[
[
2,
15
]
]
Another way is to use array_values():
while ($row = mysqli_fetch_assoc($result))
{
$vals = array_values($row);
$vals = array_map('intval', $vals);
$json_array[] = $vals;
}
Related
I'm trying to get a verification array to populate before mysql array in json_encode. this is the Array I would like before the mysql array "array("status":"true","message":"Data fetched successfully!","data":" But when I run the web service it just comes up blank. Any ideas?
<?php
// Create connection
$con=mysqli_connect("localhost","burtkunt_dbuser","phatelives","burtkunt_colors");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM colors";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode(array("status":"true","message":"Data fetched successfully!","data":$resultArray));
}
// Close connections
mysqli_close($con);
?>
This is what I'd like it to look like:
{"status":"true","message":"Data fetched successfully!","data":[{"id":"1","name":"Roger Federer","country":"Switzerland","city":"Basel","imgURL":"https:\/\/demonuts.com\/Demonuts\/SampleImages\/roger.jpg"},{"id":"2","name":"Rafael Nadal","country":"Spain","city":"Madrid","imgURL":"https:\/\/demonuts.com\/Demonuts\/SampleImages\/nadal.jpg"},{"id":"3","name":"Novak Djokovic","country":"Serbia","city":"Monaco","imgURL":"https:\/\/demonuts.com\/Demonuts\/SampleImages\/djoko.jpg"},{"id":"4","name":"Andy Murray","country":"United Kingdom","city":"London","imgURL":"https:\/\/demonuts.com\/Demonuts\/SampleImages\/murray.jpg"},{"id":"5","name":"Maria Sharapova","country":"Russia","city":"Moscow","imgURL":"https:\/\/demonuts.com\/Demonuts\/SampleImages\/shara.jpg"},{"id":"6","name":"Caroline Wozniacki","country":"Denmark","city":"Odense","imgURL":"https:\/\/demonuts.com\/Demonuts\/SampleImages\/woz.jpg"},{"id":"7","name":"Eugenie Bouchard","country":"Canada","city":" Montreal","imgURL":"https:\/\/demonuts.com\/Demonuts\/SampleImages\/bou.png"},{"id":"8","name":"Ana Ivanovic","country":"Serbia","city":"Belgrade","imgURL":"https:\/\/demonuts.com\/Demonuts\/SampleImages\/iva.jpg"}]}
your array is in incorrect format as
this is correct format
$array = array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
$json_arr = array("status"=>"true","message"=>"Data fetched successfully!","data"=> $resultArray);
echo json_encode($json_arr);
Your PHP array assignment is incorrect. Besides, I have found some other issue with your code. Here is an improved version
<?php
// Create connection
$con=mysqli_connect("localhost","burtkunt_dbuser","phatelives","burtkunt_colors");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM colors";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
// $tempArray = array(); // unnecessary
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
// $tempArray = $row;
array_push($resultArray, $row);
}
// Finally, encode the array to JSON and output the results
echo json_encode(array("status" => "true","message" => "Data fetched successfully!","data" => $resultArray));
}
// Close connections
mysqli_close($con);
?>
You must select it first all value your database inside while like this
This my way to make json when select data from DB
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
$data = array("id" => $row['id'], "name" => $row['name'],"country" => $row['country']);
array_push($temparray, $data);
}
$arr= array("status"=>"true","message"=>"Data fetched successfully!", "data" => $temparray);
echo json_encode($arr);
Hope it help
I am working on a feature of my website where I need to trigger an ajax call on the click of button. I am receiving data in this format:
Object {
name: "abc",
category_id: "1"
}
I want a result like this:
{
"list" : [
{
"name" : "xyz",
"category_id" : "1"
}, {
"name" : "abc",
"category_id" : "11"
}
]
}
my server side code is:
<?php
header('Content-Type: application/json');
$conn = mysqli_connect("localhost","root","","test") or die(mysqli_error());
$name = $_GET['name'];
$sql = "SELECT * from test_search where name = '$name'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result)) {
$name = $row['name'];
$category = $row['category_id'];
}
$data = array("name" => $name , "category_id" => $category );
echo json_encode($data);
?>
Before, you were assigning $row array items to variables, and then not using them until after the loop. After the loop, you used those variables, but it would only have the last values. You must append your items to an array ('list') inside of your array and then json_encode() your result from the loop to get the desired effect.
<?php
$conn = mysqli_connect("localhost","root","","test") or die(mysqli_error());
$name = $_GET['name'];
header('Content-Type: application/json');
$sql = "SELECT * from test_search where name = '$name'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
$data_array = array('list' => array());
while($row = mysqli_fetch_array($result))
{
$data_array['list'][] = array("name" => $row['name'], "category_id" => $row['category_id'] );
}
echo json_encode($data_array);
?>
Untested code, apologies for any syntax errors.
I would also like to point out that your code is open to SQL injection attacks. Follow the link to the PHP Manual to learn more about these and how to prevent them.
You need to push $name and $category variables into another array - currently you're simply overriding those values in your while loop.
Do something like:
$list = array();
while($row = mysqli_fetch_array($result))
{
$list[] = array('name'=>$row['name'], 'category_id'=>$row['category_id']);
}
$data = array('list'=>$list);
echo json_encode($data);
Have a read about PHP arrays here - http://php.net/manual/en/function.array.php
Also before you jump straight to json_encode($data), try var_dump($data) see what you're working with.
You need to build the array in your while loop,
$data = [];
while($row = mysqli_fetch_array($result)) {
$data['list'][] = [
'name' => $row['name'],
'category' => $row['category']
]
}
echo json_encode($data);
Untested, but should give you what you need.
I have seen many examples but I cannot properly echo what I am looking for. My goal is to convert the BLOB into base64 and echo the JSON array using php. I am aware that storing images in the database as BLOB is not generally the proper approach but I want to do this just for the sake of knowing how to do it (general consensus seems to be that storing references to the images which in turn are stored in the file system is the better approach). I am also well aware that there are probably multiple security issues in my php code (very new to php). I would just like to know this.
Here is the structure of my table:
http://s27.postimg.org/lod0ec0er/Screen_Shot_2015_05_13_at_10_49_29_PM.png
Here are the contents of my table:
http://s15.postimg.org/joks2fvzv/Screen_Shot_2015_05_13_at_10_51_34_PM.png
Here is my first php code attempt (before realizing that I had to convert the BLOB to base64):
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM TestImages";
if($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
mysqli_close($result);
mysqli_close($con);
?>
Here is what the above code displays (I believe image is null because JSON cannot naturally handle BLOB):
htttp://s2.postimg.org/k2vi3r0ft/Screen_Shot_2015_05_13_at_10_52_06_PM.png
After realizing that I have to convert BLOB to base64 here is my modified php code:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM TestImages";
if($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$row["image"] = base64_encode($row["image"]);
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
mysqli_close($result);
mysqli_close($con);
?>
The above code does not even produce an empty set. It is completely blank. What am I doing wrong in my code?
There is a mistake in the while loop.
You are changing the value of your row variable inside the loop which I hope invalidates the condition in the while loop and the control comes out of the loop. You have stored the base64encoding result in a different variable.
while($row = $result->fetch_object()) { $row_encoding = base64_encode($row["image"]); $tempArray = $row_encoding; array_push($resultArray, $tempArray); }
So I want to export a JSON file from a MySQL database table, a php script that runs weekly and exports JSON file from a specific table.
This is sort of the thing I want to achieve:
<?php
$json_file_name = "File_export.json";
$json_file_name = str_replace(" ", "_", $json_file_name);
$con = mysqli_connect("", "", "", "");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date_range = array(
"start" => date("Y-m-d H:i:s", strtotime("-7 days")),
"end" => date("Y-m-d H:i:s", strtotime("now")),
);
and so on
if(!empty($json_data) && count($json_data) > 1)
{
$json_file_data = "";
$fp = fopen($json_file_name, 'w');
foreach($json_data as $row)
{
$json_file_data .= implode(",", $row) . "\n";
}
fwrite($fp, $json_file_data);
fclose($fp);
What is the best way to achieve the same.
Thank you :)
If your database table not too large, you can fetch all rows into a single array, then turn that array into JSON automatically without looping. This will generate JSON with column values as a list:
// $con is connection, $json_filename is name of filename to write
$query = "select * from MyTable";
// Fetch all rows into $json_data array
$result = mysqli_query($con, $query);
$json_data = mysqli_fetch_all($result);
mysqli_close($con);
// Turn data into JSON and write to file
$json = json_encode($json_data);
file_put_contents($json_filename, $json);
Example output:
[["name1","address1"],["name2","address2"]]
If your database table is a little bigger, it is better to write each line as it is generated. The code below will create a JSON object for each row.
$query = "select * from MyTable";
$result = mysqli_query($con, $query);
// Open output file
$fp = fopen($json_file_name, 'w');
// Write JSON list start
fwrite($fp, '[');
// Write each object as a row
$isFirstRow = true;
while ($row = mysqli_fetch_assoc($result)) {
if (!$isFirstRow) {
fwrite($fp, ',');
} else {
$isFirstRow = false;
}
fwrite($fp, json_encode($row));
}
// Write JSON list end
fwrite($fp, ']');
// Close file and MySQL connection
fclose($fp);
mysqli_close($con);
Example output:
[{"name": "name1", "address": "address1"},{"name": "name2", "address": "address2"}]
I think you also want to change this line:
$json_file_data .= implode(",", $row) . "\n";
to this:
$json_file_data[] = implode(",", $row);
Which will cause this:
$json = json_encode($json_data);
To deliver a json array of your database rows.
My mind got stuck when i try to develope this:
i have a table in my database called "article" whit two column, "name" and "price".
How can i extract all rows from my table and echo all column in JSON?
i really can't understand how to convert result in JSON. My mind it's stuck like never before. i need to echo something like this:
{"items": {
"items":[
{"name": "firstitemname",
"price": "5"
},
{"name": "secondone",
"years": "3"
}],
}}
Please help me fixing my buggy code!
<?php
$query = mysql_query("SELECT * FROM itemlist");
$nameitem = array();
$itemprice = array();
while($row = mysql_fetch_array($query)){
array_push($nameitem , $row['nome']);
array_push($itemprice, $row['pix']);
}
?>
You would simply edit your PHP as follows.
<?php
$query = mysql_query("SELECT * FROM itemlist");
$items = array();
while($row = mysql_fetch_array($query)){
$items[] = array('name' => $row['nome'], 'price' => $row['pix']);
}
echo json_encode(array('items'=>$items));
?>
http://php.net/manual/en/function.json-encode.php
JSON is super easy to deal with in PHP.
If you're using PHP 5.2 or greater, you can use the json_encode function to do exactly what you're trying to do: http://www.php.net/manual/en/function.json-encode.php
For your code, you should be able to do something like this:
$query = mysql_query("SELECT * FROM itemlist");
$json_output = array();
while($row = mysql_fetch_assoc($query)){
$json_output[] = json_encode($row);
}
Here, $json_output will contain an array of strings with the json encoded string of each row as each array element. You can output these as you please.
<?php
$result = mysql_query("select * from item_list");
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
print json_encode($rows);
?>
Convert Data table to json with following code :
echo(json_encode($array));
for example ( select data from mysql and convert to json ):
public function SELECT($tableName,$conditions){
$connection = mysqli_connect($hostname, $userName, $password,$dbName);
try {
if (!$connection)
die("Connection failed: " . $connection->connect_error);
else
{
$qry = "";
if(!$this->IsNullOrEmptyString($conditions))
$qry = "SELECT * FROM `".$tableName."` WHERE ".$conditions;
else
$qry = "SELECT * FROM `".$tableName."`";
$result = mysqli_query( $connection, $qry);
if($result) {
$emparray = array();
while($row =mysqli_fetch_assoc($result))
$emparray[] = $row;
echo(json_encode($emparray));
}
else
echo(mysqli_error($connection));
}
mysqli_close($connection);
} catch(Exception $ex) {
mysqli_close($connection);
echo($ex->getMessage());
}
}