Creating a php associative array that can be json encoded - php

Ok so I have a could similar to this.
<?php
$con = mysqli_connect("localhost", "user", "password", "DB");
if (mysqli_connect_errno()){
echo "failed to connect:" . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM DB");
$cars = while($row = mysqli_fetch_assoc($grab)){
"id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"];
}
json.encode($cars);
So I know that the while loop is a bit strange, but I need to know how I adjust the code so I can json encode the resulting variable, so I get an array of associative arrays.
I know this code wont work but how do I get it to work, I'm guessing its going to take a little more work, but am very new to coding and php.
Any help would be appreciated, thanks.

$cars = array();
while($row = mysqli_fetch_assoc($grab)){
$cars[] = array("id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"]);
}
json_encode($cars);
this is correct syntax and method

Close?
$the_array = array();
while($row = mysqli_fetch_assoc($grab)) {
$temp = array();
$temp['id'] = $row['Id'];
$temp['name'] = $row['Name'];
$temp['color'] = $row['Color'];
$the_array[] = $temp;
}
json_encode($the_array);

mysql methods are depreciated in PHP, try to use PDO extension.
Use the following
$grab = mysql_query($con, "SELECT * FROM DB");
$cars = array(); $i = 0;
while($row = mysql_fetch_array($grab))
$cars[$i++] = array("id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"]);
header('Content-Type: application/json');
json.encode($cars);

Related

convert large data in json format

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;

data in correct json format

I am working on a feature of my website where I need to trigger an ajax call on the click of button. I am receiving data in this format:
Object {
name: "abc",
category_id: "1"
}
I want a result like this:
{
"list" : [
{
"name" : "xyz",
"category_id" : "1"
}, {
"name" : "abc",
"category_id" : "11"
}
]
}
my server side code is:
<?php
header('Content-Type: application/json');
$conn = mysqli_connect("localhost","root","","test") or die(mysqli_error());
$name = $_GET['name'];
$sql = "SELECT * from test_search where name = '$name'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result)) {
$name = $row['name'];
$category = $row['category_id'];
}
$data = array("name" => $name , "category_id" => $category );
echo json_encode($data);
?>
Before, you were assigning $row array items to variables, and then not using them until after the loop. After the loop, you used those variables, but it would only have the last values. You must append your items to an array ('list') inside of your array and then json_encode() your result from the loop to get the desired effect.
<?php
$conn = mysqli_connect("localhost","root","","test") or die(mysqli_error());
$name = $_GET['name'];
header('Content-Type: application/json');
$sql = "SELECT * from test_search where name = '$name'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
$data_array = array('list' => array());
while($row = mysqli_fetch_array($result))
{
$data_array['list'][] = array("name" => $row['name'], "category_id" => $row['category_id'] );
}
echo json_encode($data_array);
?>
Untested code, apologies for any syntax errors.
I would also like to point out that your code is open to SQL injection attacks. Follow the link to the PHP Manual to learn more about these and how to prevent them.
You need to push $name and $category variables into another array - currently you're simply overriding those values in your while loop.
Do something like:
$list = array();
while($row = mysqli_fetch_array($result))
{
$list[] = array('name'=>$row['name'], 'category_id'=>$row['category_id']);
}
$data = array('list'=>$list);
echo json_encode($data);
Have a read about PHP arrays here - http://php.net/manual/en/function.array.php
Also before you jump straight to json_encode($data), try var_dump($data) see what you're working with.
You need to build the array in your while loop,
$data = [];
while($row = mysqli_fetch_array($result)) {
$data['list'][] = [
'name' => $row['name'],
'category' => $row['category']
]
}
echo json_encode($data);
Untested, but should give you what you need.

php implode two tags into one array

I want to have one array from these two tags so I can reference it through my client using either tag from the index
$query = "SELECT username,imgDefault from users"
$result = $sql->query($query);
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[]=$row;
}
$result->close();
$sql->close();
$str = implode(',', array_map(function($el){ return $el['username']; }, $rows));
$str1 = implode(',', array_map(function($el){ return $el['imgDefault']; }, $rows));
Desired Output Array
username:"d" imgDefault: "a", username:"b" imgDefault: "q", etc....
Im open to any other output that would help me identify the column value on an index
If I understood correctly what you're trying to do is to have the possibility to get a "username" based on a "imgDefault" OR to get a "imgDefault" based on a "username".
You should first get an associative array where the key is the username, and the value is the imgDefault:
$query = "SELECT username,imgDefault from users"
$result = $sql->query($query);
$associativeArray = array();
while($row = $result->fetch_assoc()) {
$currUsername = $row["username"];
$currImgDefault = $row["imgDefault"];
$associativeArray[$currUsername]= $currImgDefault;
}
$result->close();
$sql->close();
// $array will look like array("d" => "a", "b" => "q", ...);
Then you can look for a "imgDefault" based on a "username" using:
if (array_key_exists($theUsername, $associativeArray))
{
$theImgDefault = $associativeArray[$theUsername];
}
And you can look for a "username" based on a "imgDefault" using:
$theUsername = array_search($theImgDefault,$associativeArray);

get values as array

$sql=mysql_query("select cost from projectdetails");
while($row=mysql_fetch_assoc($sql))
{
$data=$row['cost'];
}
This is my php code Can you help me how to get like this,,
$data = array("0" => 898, "1" => 1498, "2" => 1343,"3" => 1345, "4" => 1045, "5" => 1343, "6" => 987);
Just $data[] = $row['cost']; and you'll get $data as an array
Try this:
$count = 0;
$sql=mysql_query("select cost from projectdetails");
while($row=mysql_fetch_assoc($sql)) {
$data[$count]=$row['cost'];
$count++;
}
First of all you should use PDO, its much better, try this
//edit for your server/database
$username = "username";
$password = "password";
$hostname = "hostname";
$dbname = "database-name";
//to connect to the database
$db = new PDO('mysql:host='.$hostname.';dbname='.$dbname.';charset=utf8', $username, $password);
Then the query is very simple
$query = "SELECT cost FROM projectdetails;";
$sth = $db->prepare($query);
$sth->execute();
$data = $sth->fetchAll();
And now you have all your $data as an array, you can loop through it, assign different values or whatever you want.

How to retrive php data from mysql and convert it to json?

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

Categories