How can I echo a BLOB using JSON array in php? - php

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); }

Related

Having an array before encoding mysql array

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

Passing Data from Swift to PHP for JSON using file_get_contents?

I am new to Swift 3 and I am trying to pass some data to server using PHP. I am a beginner in both languages to be sure.
I am trying to receive a data from SWIFT to PHP.
However, I realized that with $_POST or $_REQUEST in PHP would not work for JSON. Instead, I heard that it is necessary to use 'file_get_contents' or 'PHP://input'.
So I seriously spent a lot of hours on figuring out how to make it work.
The following is the code from the PHP side. However, it seems to be working only with the Raw Data, not with JSON encode.
Does anyone think the code below is incorrect to receive the data from SWIFT?
<?php
header("Content-Type: application/json");
$con=mysqli_connect("localhost","123","123!!","123");
$menu_main_item_store_id = file_get_contents('php://input');
$menu_main_item_store_id_received = $menu_main_item_store_id;
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM menu_main_items WHERE menu_main_item_store_id=$menu_main_item_store_id_received AND menu_main_item_in_use_check = 'yes'";
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($con);
?>
file_get_contents('php://input') will give you a string containing whatever data was posted to PHP. It will not automatically work out what format that data is in, so you'll need to parse the data somehow, e.g. with json_decode().
Remember to check for errors in the JSON formatting, and that all input is untrusted - you don't know for sure that it's your app sending the data, somebody could figure out the URL and send something weird to break your PHP code.
Swift seems to be sending correct data using POST.
let url:NSURL = NSURL(string: url)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
let paramString = "table_id='1'"
request.httpBody = paramString.data(using: String.Encoding.utf8)
However, when the PHP receives it,
it returns nothing.
$contents = $_REQUEST['table_id'];
$abc = $contents;
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM menu_main_items WHERE table_id='".$abc."'";
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);
}
If I manually type $content="1"; then the data is retrieved.
What do you think the problem seems to be?
// You Can try this code
<?php
define('HOST','localhost');
define('USER','DatabaseUserName');
define('PASS','Password');
define('DB','DataBaseName');
$con = mysqli_connect(HOST,USER,PASS,DB);
$sql = "select * from DATABAS_TABLE_NAME";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('Username'=>$row[0],
'Cell'=>$row[1],
));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>

Retrieve Value of a single column

I need to retrieve data from a single column and put in an API (Json), but for some reason I get the title from the column as well.
$sql = "SELECT workingJson FROM dataTable";
I assumed it would be like workingJson.Value, but no luck.
Here is the API.php
// Create connection
$con=mysqli_connect("localhost","user","password","database");
// 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 column1 FROM database";
// 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($resultArray);
}
// Close connections
mysqli_close($con);
Edit per your comments:
To just return the values and not the keys in PHP, you could change your code to this:
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add value to array
array_push($resultArray, $row->column1);
}
You have no need for $tempArray in this case.
you can get all results and after doing a traitment :
<?php
// Create connection
$con=mysqli_connect("localhost","user","password","database");
// 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 column1 FROM database";
if ($result = $mysqli->query($sql)) {
//get all fields :
$finfo = $result->fetch_fields();
foreach ($finfo as $val) {
$resultArray[] = $val->column1;
}
$result->close();
}
// Finally, output the results without encode because is also in json format:
echo '{'. implode(','.chr(10), $resultArray) .'}';
$mysqli->close();

make json array from mysql data using php

I want to take some data from my mysql database, and pass it to a json array, so that I can use it in my android application.
But so far I'm having trouble getting any data from the mysql db, when i run my php code in the browser to check output, i get a blank screen. Can someone help ?
CODE:
<?php
$connection = mysqli_connect("localhost","testUser","root","EasyFridge") or die("error". mysqli_error($connection));
$sql = "select * from product";
$result = mysqli_query($connection, $sql);
$emparray = array();
while($row = mysqli_fetch_assoc($result)){
$emparray[] = array("product" => $row);
}
echo json_encode($emparray);
mysqli_close($connection);
?>
I suggest you look at error log of PHP. It's very likely that the script exceeded max memory available. If so, you may try following actions:
Increase max memory in php.ini file by setting memory_limit parameter or call in your code ini_set('memory_limit', '2048M');;
Break your data into pages with more appropriate count of objects returned.
UPDATE:
Found the error, was missing a charset decoding statement, so just added:
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","testUser","root", "EasyFridge") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "SELECT * FROM product";
mysqli_set_charset($connection, "utf8"); //ADDED THIS LINE!!
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
error_reporting(E_ALL);
$returnarray = array();
//create an array
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
//$emparray[] = $row[];
$emparray['id'] = $row['id'];
$emparray['name'] = $row['name'];
$emparray['placement_date'] = $row['placement_date'];
$emparray['removal_date'] = $row['removal_date'];
$emparray['type'] = $row['type'];
array_push($returnarray, $emparray);
}
//var_dump($returnarray);
echo json_encode($returnarray);
//close the db connection
mysqli_close($connection);
?>

PHP code to encode DB data in JSON not working

I'm currently stuck with some PHP code. I want to access a table in my database and retrieve the data in a JSON format. Therefore, I tried the following code :
<?php
$con = mysqli_connect("......","username","pwd","DBName");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM users";
if ($result = mysql_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
mysqli_close($con);
?>
However, it's getting me an empty page. It worked once but only with a special number of row in the table, so not very efficient as you might guess.
Does anybody have an idea why i'm getting those weird results?
EDIT 1 :
I Just tried to add this to my code :
echo json_encode($resultArray);
echo json_last_error();
And it's returning me 5. It seems to be an error from the data encoding in my table. Therefore I added that code :
$tempArray = array_map('utf8_encode', $row)
array_push($resultArray, $tempArray);
And I got the following output : [null,null,null]0 (The zero comes from the echo json_last_error();)
So here I am, can anybody help me with this ?
I would start by changing if ($result = mysql_query($con, $sql)) to if ($result = mysqli_query($con, $sql)) because they are different database extensions
Another thing would be to change while($row = $result->fetch_object()) to while ($row = mysqli_fetch_object($result)) { (Procedural style vs. Object oriented style)
If you still see blank screen, try adding error_reporting(E_ALL); at the top of your script, and you'll be able to know exactly where the bug is
<?php
$con = mysqli_connect("......","username","pwd","DBName")
or die("Failed to connect to MySQL: " . mysqli_connect_error());
$sql = "SELECT * FROM users";
$query = mysqli_query($con, $sql) or die ("Failed to execute query")
if ($result = $query)
{
$resultArray = array();
while($row = $result->fetch_object())
{
array_push($resultArray, $row);
}
$result->close()
echo json_encode($resultArray);
}
mysqli_close($con);
?>
This code works for me, try it out:
<?php
$con = mysqli_connect("......","username","pwd","DBName");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM users";
if ($result = mysqli_query($con, $sql))
{
while($row = $result->fetch_object())
{
$resultArray[] = $row;
}
echo json_encode($resultArray);
}
mysqli_close($con);
?>
EDIT 1:
As a test replace this code:
while($row = $result->fetch_object())
{
$resultArray[] = $row;
}
echo json_encode($resultArray);
with this code:
while($row = $result->fetch_assoc())
{
print_r($row);
}
What output do you get?
I finally found a solution ! That was indeed an encoding problem, the json_encode() function accepts only strings encoded in utf8. I changed the interclassement of my table to utf8_general_ci and I modified my code as follows :
<?php
//Create Database connection
$db = mysql_connect(".....","username","pwd");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("DBName",$db);
//Replace * in the query with the column names.
$result = mysql_query("SELECT * FROM users", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['name'] = utf8_encode($row['name']);
$row_array['lastName'] = utf8_encode($row['lastName']);
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
And I got the expected output.

Categories