Retrieve Value of a single column - php

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

Related

How modify to PHP SQL SELECT query to display message depending on if data is found

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

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

exporting data in json format

I am trying to export data from PhpMyAdmin to JSON format
This code works for select lat,lng from googlemaps, but does not for the address column
My code is:
<?php
$con=mysqli_connect("localhost","root","","googlemaps");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT lat,lng,`addr` FROM infos";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row =mysqli_fetch_array($result))
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
$fp = fopen('results01.json', 'w');
fwrite($fp, "{ \"tab\": ");
fwrite($fp, json_encode($resultArray));
fwrite($fp, " }");
fclose($fp);
echo json_encode($resultArray);
//var_dump($resultArray);
?>
Screenshot of infos table:
Just found the solution it s actually adding this before the select query :
mysqli_set_charset($con, "utf8");
$sql = "SELECT lat,lng,`addr` FROM infos";
if ($result = mysqli_query($con, $sql))
{......}

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.

How can I echo a BLOB using JSON array in 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); }

Categories