BLOB field returns null JSON - php

I am saving my images directly in the database (Yes I have read about that and know it's better to save the path to the image).
The problem is selecting the image field which is a blob returns NULLto my JSON. I have alot read quite a few stackoverflow links of the same query but still not a clear explanation/ answer received has been able to help me.
I have encoded using base_64 but when doing so nothing is showed on the webpage.
Would appreciate if I could be pointed in the correct direction.
This is part of my code:
header("Content-Type:application/json");
//select query
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
if (!empty($rows))
{
$encode = array("StudentsList" => $rows);
//$json_response=json_encode($encode);
$json_response=base64_encode($encode);
echo $json_response;
echo json_last_error(); //Returns 0
}

if you need the json data
please use json_encode
example
echo json_encode($json_response);
and also read php manual
http://php.net/manual/en/function.json-encode.php

Related

How to retrieve MongoBinData to a string in PHP?

I have successfully stored an image into a MongoDB database, since it is stored as a Base64 type information; I want to retrieve that BinData to a string. How do I do that? Here I am finding my document using input 'Email'.
<?php
$m = new MongoClient();
$db = $m->mydb2->mycol2;
$result = $db->find(array('Email'=>$em));
foreach( $result as $key){
$susername = $key['Email'];
$imagebody = $key['pic'];
}
echo $imagebody;
?>
EDIT:
As Haresh has said
$imagebody = $key['pic']->bin
works perfectly. But it returns me something like Raw data but if I write this
$imagebody = base64_encode($key['pic']->bin);
then it returns me exact Base64 format.
According to Documentation
To access the contents of a MongoBinData, use the bin field which return the string Mongo Binary Data
So Try this:
$imagebody = $key['pic']->bin
Hope this works for you.

Why is my PHP script not returning valid JSON

What's wrong with the JSON available at the link below???
http://bruceexpress.com/beerstore/test/getottawaeaststorebeerlist.php
Using PHP, I generated the above JSON from an SQL query and encoded it with json_encode.
$retval = mysqli_query($connection, $sql);
if(! $retval )
{
print('Could not select: ' . mysqli_error());
}
$storearray = array();
while($row = mysqli_fetch_assoc($retval))
{
$storearray[] = $row;
}
header('Content-Type: application/json');
echo json_encode($storearray);
In SWIFT:
json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
is throwing the NSCocoaErrorDomain Code=3840 exception. "JSON text did not start with array...."
I caught the exception and printed the data, and I am seeing this:
("<!DOCTYPE html>\n[{\"beer_id\":\"1650\",\"store_id\":\"4618\"},{\"beer_id\":\"1650\",\"store_id\":\"4607\"},{\"beer_id\":\"1650\",\"store_id\":\"4616\"},{\"beer_id\":\"1650\",\"store_id\":\"4604\"},{\"beer_id\":\"5213\",
.......... ( etc. I didn't copy the whole thing. Its too long.")
I know there are many questions like this, but I am still not seeing the answer I need. What is wrong my JSON???
At first encode your php file in UTF-8 without BOM. and delete all whitespaces before <?php tag
Secondly dont print anything before if you want to send header;
Thirdly you real need some check and return in your script, because i see now at least 2 bugs which will appear in a future

Json response with php

I am trying to get JSON response using PHP. I want to have Json array not the HTML tags. But the output shows HTML tags as well.I want to remove this HTML output! PHP code is as follows: I don't know how to do this ? Please help.
Thanks in advance :)
<?php
function getFixture(){
$db = new DbConnect();
// array for json response of full fixture
$response = array();
$response["fixture"] = array();
$result = mysql_query("SELECT * FROM fixture"); // Select all rows from fixture table
while($row = mysql_fetch_array($result)){
$tmp = array(); // temporary array to create single match information
$tmp["matchId"] = $row["matchId"];
$tmp["teamA"] = $row["teamA"];
$tmp["teamB"] = $row["teamB"];
array_push($response["fixture"], $tmp);
}
header('Content-Type: application/json');
echo json_encode($response);
}
getFixture();
?>
It's difficult to tell without seeing what your output is, but there is nothing in your code which would add HTML to your response.
It sounds like the HTML is in the database, so you're getting the data as expected, and your browser is the displaying whatever html elements might be there.
You could ensure none of the rows from the database have HTML in them by using strip_tags as follows:
$tmp["teamA"] = strip_tags($row["teamA"]);
Do this for all rows which may contain html.
Sorry if this is not formatted right, I'm new to StackOverflow!
http://php.net/strip-tags

Cannot Decode JSON API response

I have built an API for my shipping quote system. I feed it values and I get rate quotes back. It works fine but I cannot decode the JSON response. I get a NULL response and I'm not sure whats up. According to validaters the JSON is correct.
So what I essentially do is encode a PHP array on one side and I want to parse that on the other side using a browser and PHP. However, I get a NULL response.
Here is the JSON. Let me know if you need more.
{"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
I just want to decode this so I can parse it. If there is another way to parse please let me know.
Also, I searched SOF and the similar issues people were having here didn't help me.
This is the code I use to generate the JSON.
<?php
//include ('mysql_connect.php');
$result = mysql_query('select * from quote where user_id = "'.$user_id.'" order by netCharge asc limit 1');
if (!$result) {
die('Could not query:' . mysql_error());
}
if (!$result) echo mysql_error();
$api_data = array();
$api_count = '0';
while ($row = mysql_fetch_array($result, MYSQLI_ASSOC)) {
$api_data[carrier] = $row['carrier'];
$api_data[charge] = $row['netCharge'];
$api_data[service_days] = $row['serviceDays'];
$api_count++;
}
$api_data = json_encode($api_data);
print_r($api_data);
?>
This is what I'm using to grab that JSON data:
<?php
$input = file_get_contents('api_request.php?dest_zip=66101&weight=200&class=50&ltl_shipment=X&Residential_Delivery=X');
echo $input;
$obj = json_decode($input);
var_dump($obj);
?>
Have you tried the following
$array = json_decode($data, true);
Your response has an extra </div> in it.
Delete the div so that's valid JSON and the decode function will work.
http://trumrates.com/trumrates/rate/quote/signin/api_request.php?dest_zip=66101&weight=200&class=50&ltl_shipment=X&Residential_Delivery=X
Yields:
{"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
</div>
Summary
The built-in function json_decode (see doc) should help. According to the official document, NULL is returned if the JSON cannot be decoded or if the encoded data is deeper than the recursion limit.
I doubt the JSON string you read is actually NOT as same as PHP reads. Please make sure the string is NOT HTML escaped. And it is very important that keys and values in a JSON should be quoted by double quote. Single quote is malformed JSON, which might be considered as syntax error.
Example
To be a good demo, I put json string in file and then decode it using test.php.
In example.json:
{"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
In test.php:
<?php
$input = file_get_contents('example.json');
echo $input;
// {"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
$obj = json_decode($input);
var_dump($obj);
// object(stdClass)#1 (3) {
// ["carrier"]=>
// string(12) "R&L Carriers"
// ["charge"]=>
// string(5) "99.13"
// ["service_days"]=>
// string(23) "Wednesday Oct. 22, 2014"
// }
When I wrote the code I used 'Enter' to give me spaces between lines of code. For some reason that translated to the JSON and that's why it wasn't working. I just deleted all the extra empty lines in my file and it worked.

Returning a blob with json

I'm trying to create a rest service for my android application where an external database returns items to be stored in the applications local database. I've got everything working except blobs are being returned as null.
this is an example of my jason response.(picture and thumbnail fields are blobs)
{"id":"2","user_id":"1","name":"testing","type":"bouldering","picture":null,"lat":"36","long":"81","alt":"41932","accuracy":"53","thumbnail":null}
Here is my php script to return the data.
<?php
require_once('config.php');
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$sql = 'select * from spot_main';
$results =$mysqli->query($sql);
$spots = array(); //array to parse jason from
while($spot = $results->fetch_assoc()){
$spots[] = $spot;
}
echo json_encode($spots);
?>
Anyone know of a solution to this problem? I know I'm not doing this the most efficient way(better to store images in the filesystem), but I need this to work.
Encode the binary data as base64 before you generate the JSON.
$obj->picture = base64_encode($binaryData);
You can then decode this in your Android application with any base 64 decoder. Since API level 8 there is a built in util class. Otherwise there are plenty of external libs you can use for targetting Android 2.1 or earlier.
you have to make BLOB to base64_encode
while($spot = $results->fetch_assoc()){
$spots[] = $spot;
}
Then prepare a foreach loop like this
foreach($spots as $key=>$value){
$newArrData[$key] = $spots[$key];
$newArrData[$key]['picture'] = base64_encode($spots[$key]['picture']);
$newArrData[$key]['thumbnail'] = base64_encode($spots[$key]['thumbnail']);
}
header('Content-type: application/json');
echo json_encode($newArrData);
It seems that json_encode works with UTF-8 encoded data only. You can use json_last_error() to detect json_encode error.

Categories