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
Related
I have the following SELECT query that shows data depending on if it exists in the mySQL table.
Right now if it does it will display all of the records found, If not it will just display nothing.
I would like to make it display if the record is found
{"error":false}
and If the record is not found
{"error":true}
The following is what I have so far:
$sql = "SELECT field1,field2
from Table1 WHERE field3 = 'Dog' ";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// Create temporary connection
$resultArray = array();
$tempArray = array();
// Look through each row
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);
}
mysqli_close($con);
How can this be achieved?
you need to initialize an array with a default value, then change the value if the records are found
$sql = "SELECT field1,field2
from Table1 WHERE field3 = 'Dog' ";
$resultArray = ['error' => true];
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// Create temporary connection
$tempArray = array();
// Look through each row
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
$resultArray['error'] = false;
}
echo json_encode($resultArray);
mysqli_close($con);
You can do something like that:
$return = [
'error' => true
];
$sql = "SELECT field1,field2
from Table1 WHERE field3 = 'Dog' ";
$result = mysqli_query($con, $sql);
if($result && $result->num_rows > 0){
$return['error'] = false;
}
mysqli_close($con);
echo json_encode($return);
I'm trying to list all rows in the database (2 currently) in JSON format, but the only output I'm getting is the last row.
Output:
[{"id":"2","Name":"Googleplex","Address":"1600 Amphitheatre Pkwy, Mountain View, CA","Latitude":"37.421999","Longitude":"-122.083954"}]
Code:
if($status == "connected") {
$locations = $db->prepare('SELECT * FROM Locations');
$locations->execute();
$result = $locations->fetch(PDO::FETCH_ASSOC);
if(!empty($result)) {
// 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 = $locations->fetch(PDO::FETCH_ASSOC))
{
// 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);
}
}
The problem is you're throwing away the first result you read in this line:
$result = $locations->fetch(PDO::FETCH_ASSOC);
You can just simplify your code to
if ($status == "connected") {
$locations = $db->prepare('SELECT * FROM Locations');
$locations->execute() or die("Unable to execute query");
$resultArray = array();
while ($row = $locations->fetch(PDO::FETCH_ASSOC)) {
$resultArray[] = $row;
}
echo json_encode($resultArray);
}
this is my php sql code
//fetch table rows from mysql db
$sql = "select * from tbl_sample";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
$info = json_encode($emparray);
echo $info;
//close the db connection
mysqli_close($connection);
?>
when I run this code i'm getting an an anonymous json array like this.
[{"id":"1","country":"india","domain":"MBA"},{"id":"2","country":"england","domain":"cricket"},{"id":"3","country":"pakistan","domain":"MTECH"},{"id":"4","country":"newzeland","domain":"bba"}]
is there a way to give this array a name because without a named array I don't know how to use this json data for dust.js template. If not suggest me how I can use this data for my templating. thank you.
//fetch table rows from mysql db
$sql = "select * from tbl_sample";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
$mydata['my_data'] = $emparray;
$info = json_encode($mydata);
echo $info;
//close the db connection
mysqli_close($connection);
Try this. Your data will look like this
{"my_data":[{"id":"1","country":"india","domain":"MBA"},{"id":"2","country":"england","domain":"cricket"},{"id":"3","country":"pakistan","domain":"MTECH"},{"id":"4","country":"newzeland","domain":"bba"}]}
When building your array, you need to setup your keys using whichever unique value you want. For example:
while($row =mysqli_fetch_assoc($result)) {
$key = $row['domain'];
$emparray[$key] = $row;
}
This will result in your JSON being keyed with the domain value.
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();
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); }