I have a JSON object that I'm POST'ING to PHP from ExtJS interface. I get the object from
$json = $_POST["newUserInfo"];
The object will contain 3 arrays, which I can see if I do
var_dump(json_decode($json));
I need to take each array and build SQL queries from them. My first obstacle is getting the arrays out of the object, though this may be unnecessary. Here is the code block I'm working from:
/*Variable passed in from the ExtJS interface as JSON object*/
$json = $_POST["newUserInfo"];
//$json = '{"USER":{"ID":"","FULL_USER_NAME":"Some Guy","ENTERPRISE_USER_NAME":"guyso01","USER_EMAIL":"Some.Guy#Email.com","USER_PHONE":"123-456-7890"},"PERMISSIONS":{"ID":"","USER_ID":"","IS_ADMIN":"true"},"SETTINGS":{"ID":"","USERS_ID":"","BACKGROUND":"default"}}';
//Test to view the decoded output
//var_dump(json_decode($json));
//Decode the $json variable
$jsonDecoded = json_decode($json,true);
//Create arrays for each table from the $jsonDecoded object
$user_info = array($jsonDecoded['USER']);
$permissions_info = array($jsonDecoded['PERMISSIONS']);
$settings_info = array($jsonDecoded['SETTINGS']);
I'm not creating the arrays correctly. I've also tried
$user_info = $jsonDecoded->USER;
and that doesn't work either. I'm sure I'm missing something easy here. Again, this may be unnecessary as I can probably access them directly. I need to build the query by looping through the array and appending each key to a string and each value to a string. So I'd end up with something like
$query = "INSERT INTO USERS ($keyString) VALUES ($valueString);
Then I'd repeat the same process for PERMISSIONS and SETTINGS arrays. This is probably simple but I'm stuck here.
If you are using json_decode($json,true); - true means returning the js objects results as associative arrays - then all you have to do is $user_info = $jsonDecoded['USER']; without the array() cast cause that is what json_decode do for you.
If you would choose to omit the second boolean parameter then you will get an stdClass which $jsonDecoded->USER; would work for you
Related
I new in PHP programming and I try to make simple API with simple PHP. Below my snippet code :
$con = mysqli_connect(HOST, USER, PASS, DB);
$sql_results = mysqli_query($con, "SELECT * FROM `table-images`");
$rows = array();
while($r = mysqli_fetch_assoc($sql_results)) {
$rows[] = $r;
}
echo'{"response":'.json_encode($rows).'}';
The code above have JSON output like below :
{"response":[{"id":"31","shirtImage":"Content\/Images\/Short Sleeve\/874be7b82812f76c944d71706c9651eb.gif"},{"id":"32","shirtImage":"Content\/Images\/Short Sleeve\/b-Cleaned.png"}]}
I want to know why value of field shirtImage have extra symbol \ . In my database the value is correct example Content/Images/Short Sleeve/b-Cleaned.png but when it encode to JSON the output have changed. How to fix this?
I find some keyword regarding my case, but it still does not work.
There is nothing to fix.
JSON is a format that encodes a data structure in a way that makes it storable and transportable. When the data is needed for processing you have to decode it from JSON.
You can use json_decode() in PHP or JSON.parse() in JavaScript to restore the original data and work with it.
Many other languages provide a function or library to work with JSON.
You should not generate JSON manually. The correct way to produce a JSON from your data is:
$response = ['response' => $rows];
echo json_encode($response);
Because the values stored in $rows are arrays (and because it is easier to work with arrays in PHP than with bare objects) when you decode the JSON in PHP it's recommended to pass true as the second argument to json_decode(). This way it uses arrays in the restored data structure.
Otherwise it produces instances of stdClass which are bare PHP objects. The arrays are more versatile.
json_encode() escapes forward slash. Try using:
echo'{"response":'.json_encode($rows, JSON_UNESCAPED_SLASHES).'}';
Its due to escaping / with `\` and it will be removed when you decode your json back.
Try to decode it back.
$d = json_decode('{"response":[{"id":"31","shirtImage":"Content/Images/Short Sleeve/874be7b82812f76c944d71706c9651eb.gif"},{"id":"32","shirtImage":"Content/Images/Short Sleeve/b-Cleaned.png"}]}');
print_r($d);die; // This will give you the original data with out `\`
I see many questions about passing an array as a query string in PHP, and it seems the prevailing way is using brackets as in key[]=foo&key[]=bar.
However I cannot find a straight answer about how to send an object (or a key=>value associative array - same thing) as a query string.
Currently, however I do it is:
STRING
?foo=bar&hello=world
Then on the server side, I would do:
<?php
$array = array();
$array['foo']=$_GET['foo'];
$array['hello']=$_GET['hello'];
?>
Of course when using $_POST, this is very simple with an ajax request. Any object you send automatically serializes and isn't a problem.
Is this the best way to handle it, or is there some other standard for sending an object in a query string using PHP?
You can use an associative array in a form and in the query string:
object[foo]=bar&object[hello]=world
To build it URL encoded:
$data['object']['foo'] = 'bar';
$data['object']['hello'] = 'world';
echo http_build_query($data);
Yields:
object%5Bfoo%5D=bar&object%5Bhello%5D=world
You can go many levels and/or use dynamically added elements. In general, in text form, it looks just like a PHP array
object[foo][more][even more][]
Or:
object[foo][][more][even more]
I have an array of 'servers' that I'm storing in a JSON file.
The JSON file looks like this:
{"1":{"available":1,"players":0,"maxplayers":4}}
I retrieve this value with this:
$servers = (array) json_decode(file_get_contents("activeservers.json"));
However, when I try to access the array with $server = $servers[$id], $server is null. I noticed that the key is in quotes, so I also tried casting $id to a string, and surrounding it with quotes (") which didn't work.
Something to note, is that this code is returning "NULL":
foreach(array_keys($servers) as $key){
var_dump($servers[$key]);
}
Your code is wrong. Also you don't need to type cast when doing a json_decode, you can instead set the second parameter to true more info here.
Also you don't need to use the array_keys function in your foreach loop,
try this.
$json = '{"1":{"available":1,"players":0,"maxplayers":4}}';
$servers = json_decode($json, true);
foreach($servers as $key => $value) {
print $value["available"];
}
Do a print_r($value) to get all the array keys available to use. Also you could take advantage of the $key variable to print out the array key of the parent array.
Thanks, #Rizier123 (who solved the question).
Apparently passing TRUE as the second parameter to my json_decode function fixes the issue.
After checking the PHP documentation for json_decode() (PHP: json_decode), it seems that passing this parameter means that the resulting decoded array is automatically converted into an associative array (and this is recurring, meaning that this automatically happens for sub-arrays).
Edit: #Rizier123 also says that "you might want to read: stackoverflow.com/a/10333200 to understand a bit better why it is so "weird" and your method didn't work properly."
I sent POST request to my web-server with a few JSON-Params within the params there is an array. I receive for in the POST array-variable:
$ids = $_POST['id_arr']; // contains: [{\"id\":12},{\"id\":13}]
I don't know how to parse this to an array in PHP. I tried to solve it with json_decode, but it seems like the wrong way.
My desired result is this: $ids = array(12, 13);
How can I do this?
You need to tell the json_decode function to convert the objects to associative arrays. As shown in the json_decode documentation, this can be done by setting to true the second argument:
$ids = json_decode($_POST['id_arr'], true);
Disregarding security issues (for now)
I am using json_encode to display the contents of a select query.
I used:
$sql= {query code};
// created a temp array to hold data and an array for all the results
$resultArray = array();
$tempArray = array();
// looped through every object in the result set
while ($row = $result->fetch_object());
// added it into the results array
$tempArray = $row;
array_push($resultsArray, $temparray);
// encoded the array to a json format
echo json_encode($resultArray);
Question: My objects don't have names, so it makes it difficult for me to write any code that could read the results and display them. How do I name the objects? Is it an entry I could add into the table (let's say in a case of different names I could give each object)
You should try to build the array/object structure you want in PHP. That way when you json_encode it, you'll know what it looks like and it will be what you want.
Try:
echo json_encode(array('people' => $resultArray));
In fact this should not work at all. Casting PDO (or MySQLi, as mentioned in comment) objects to JSON. You should use fetch_assoc instad, that would return associative array that could be put directly in JSON structure.