i have a table named mobile in which all the mobile data is contained which have more then 7000 records now i want to display in json format but some how records are not showing here is my code kindly check ..
<?php
$conn = mysqli_connect("localhost","root","","test") or die ("Error ".mysqli_error($conn));
$sql = "select * from mobile";
$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
var_dump($result);
$myArray = array();
while($row = mysqli_fetch_assoc($result)){
$myArray[] = $row;
}
mysqli_close($conn);
header('Content-Type: application/json');
//$json = file_get_contents('json.json');
/*
$myArray = array("user1" => array("firstName" => "Mike2", "lastName" => "Smith" , "age" => 34),"user2" => array("firstName" => "Mike2", "lastName" => "Smith" , "age" => 34));
*/
$json = json_encode($myArray);
echo $json;
?>
table
The problem with JSON_ENCODE in PHP is, it tends to add double quotes and escaping sequences which would increase the actual size of the JSON being imported. So, please try this. This worked for me.
<?php
header('Content-Type: application/json');
$conn = mysqli_connect("localhost","root","","test") or die ("Error ".mysqli_error($conn));
$sql = "select * from mobile";
$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
$myArray = array();
while($row = mysqli_fetch_assoc($result)){
$myArray[] = $row;
}
mysqli_close($conn);
$prefix = '';
echo '[';
foreach($myArray as $row) {
echo $prefix, json_encode($row);
$prefix = ',';
}
echo ']';
?>
I assume you are probably using ajax to get your data in the browser you have used a var_dump() in your php code followed by the json headers followed by the json result which will not work.
In order to set headers , the header() function should be called first before printing out any other thing, also you do no need to put in the var dump. Try the following code:
<?php
$conn = mysqli_connect("localhost","root","","test") or die ("Error ".mysqli_error($conn));
$sql = "select * from mobile";
$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
$myArray = array();
while($row = mysqli_fetch_assoc($result)){
$myArray[] = $row;
}
mysqli_close($conn);
header('Content-Type: application/json');
$json = json_encode($myArray);
echo $json;
?>
You can do this by following way:
var obj = JSON.parse($myArray);
echo obj;
Related
Am fetching values from mysql to json. All my data's are showing properly now i want to display database name inside json. any help can be appreciated.
json.php code :
<?php
$connect = mysqli_connect("localhost", "root", "", "recruiter");
$sql = "SELECT * FROM recruiter";
$result = mysqli_query($connect, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo (json_encode($json_array));
?>
Output:
{
"here i want db name":[
{
"job_id":"1",
"job_title":"Java developer",
"job_description":"Java description",
"job_details":"details",
"job_skills":"java",
"job_min_exp":"0 Yr",
"job_max_exp":"2 Yrs",
"company_name":"",
"job_location":"",
"industry":"",
"department":"",
"job_role":"",
"owner_name":"",
"owner_mobile":"",
"owner_email":"",
"owner_description":" "
}
]
}
As per your output, Understand is database name is array under the multidimensional array. To show database name inside the JSON.
Try this code
<?php
$database_name = "recruiter";
$connect = mysqli_connect("localhost", "root", "", $database_name);
$sql = "SELECT * FROM recruiter";
$result = mysqli_query($connect, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode(array($database_name => array($json_array)));
?>
I would like to retrieve objects from the database in JSON using PHP and MySql. I would just like to know how to do this without having to create an array? Can it be done?
If so, can I get an example of how that can be done with this draft piece of code?
$sql = "SELECT Email , FirstName, LastName,Contact FROM tblUser where UserID=sessionID";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array ($result)) {
$arr = array(
$row["Email"],
$row["FirstName"],
$row["LastName"],
$row["Contact"]
);
array_push($json, $arr);
}
$jsonstring = json_encode($json);
echo $jsonstring;
$sql = "select name,email from contact";
$res = mysqli_query($conn,$sql) or die(mysqli_error($conn));
$num = mysqli_num_rows($res);
$json = array();
if($num > 0)
{
while ($obj=mysqli_fetch_object($res))
{
$json[] = $obj;
}
}
echo json_encode($json);
output:
[{"name":"test","email":"test#gmail.cmom"},{"name":"test1","email":"test1#gmail.cmom"}]
I have the following query that is returning:
"Code1""Code2""Code3"
What I need is for the result to be in CSV format like this:
'Code1','Code2','Code3'
How do I modify my code to accomplish this?
<?php
$conn = new mysqli("127.0.0.1", "user", "password", "table", "3306");
if(mysqli_connect_errno($conn)) {
echo "Unable to connect to database server";
}
$result = mysqli_query($conn,"SELECT code FROM sourcecodes");
while($row = $result->fetch_assoc()) {
$mydata = ($row['code']);
echo json_encode($mydata);
}
$result->free();
$conn->close();
?>
Per every iteration you should be pushing to an array. Once the array is built, you can turn it into json and echo it.
$mydata = array();
while ($row = $result->fetch_assoc()) {
$mydata[] = $row['code'];
}
$json = json_encode($mydata);
$string = str_replace(array('[', ']'), '', $json);
echo $string;
Try this
<?php
$conn = new mysqli("127.0.0.1", "user", "password", "table", "3306");
if(mysqli_connect_errno($conn)) {
echo "Unable to connect to database server";
}
$result = mysqli_query($conn,"SELECT code FROM sourcecodes");
while($row = $result->fetch_assoc()) {
$mydata[] = $row['code'];
}
$result->free();
$conn->close();
echo "'".implode("','",$mydata)."'";
?>
Or you need json_encode?
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.
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());
}
}