I am implementing Backbone.js, and I am just trying to understand how the sync function works.
To keep it very simple, here is the model.
var Item = Backbone.Model.extend({
defaults: {
name: "Goo"
},
url: "commlink.php"
});
and then
Backbone.sync("create", item);
This is my commlink.php
$item=json_decode($_POST);
$name=$item->name;
$results=$mdb2->query("INSERT INTO list VALUES (NULL, '$name')");
I see a new row show up in my DB, however, the field "name" is blank.
I tried both item.save() and the above method...both ended up with the same blank cell but a new entry.
This is the error in chrome in network/content:
<b>Warning</b>: json_decode() expects parameter 1 to be string, array given in ...XXX...
This is in the request payload:
{"name":"Goo"}
$rawJSONString = file_get_contents('php://input');
$item = json_decode($wrapperString);
//$item->name is the data you want
$item = json_decode(file_get_contents('php://input'), true);
print_R($item);
Found this is more helpful
https://coderwall.com/p/vwvy_a
SECURITY NOTE: as pointed out in the comment this is not the way you should ACTUALLY insert the user provided content into your database, this is simply to show you how to get access to the array information as JSON, you should use prepared statements, a framework database adapter, or some other appropriate solution for escaping the user provided content before sticking it into the database.
You're trying to run an array ($_POST) through a function (json_decode) that only accepts a string. The solution in this specific example would be to do this:
$results=$mdb2->query("INSERT INTO list VALUES (NULL, '{$_POST['name']}')");
This would work because you're accessing $_POST as the associative array that it is.
However what I think you actually want to do is first convert the $_POST array to json, then decode it so you can use it the way you wanted to (accessing it as an object, which the json_decode returns):
$item=json_encode($_POST);
$item=json_decode($item);
$name=$item->name;
$results=$mdb2->query("INSERT INTO list VALUES (NULL, '$name')");
For reference:
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/function.json-encode.php
Related
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 simply want to know how to access array elements retrieved from a database. I have the following code to get the names of each item in my database.
$plat_options = $this->db->get('tblplatform_options')->select('name')->result();
How do I go about accessing the name from the array $plat_options? Typically I would do $plat_options[0] for the first element in C#, how is this done in php/codeigniter?
In PHP/Codeigniter, can be done in the same way:
$plat_options[0] //if you have this element, usually is better to check if exists.
You can retrieve all the elements with foreach($plat_options as $option){...}
You can cast to object: https://www.kathirvel.com/php-convert-or-cast-array-to-object-object-to-array/
Or use a Codeigniter Helper (assuming you are using CI3): http://www.codeigniter.com/user_guide/helpers/array_helper.html
I recomend to know which is your array format and retrieve that way (if you don't know, you can do a: var_dump($plat_options) ) to know if is an associative array.
You can use the result_array() function:
$data = $plat_options->result_array();
echo($data[0]['name']);
or:
$data = array_shift($q->result_array());
echo($data['name']);
I extracted this last part from: Codeigniter $this->db->get(), how do I return values for a specific row? that you could check too.
If you don't know a lof of CI, the best you can do is do a simple tutorial to understand how the data + ActiveRecord works.
Hope it helps!
I am using a jQuery plugin of nestable forms and storing the order of these in a database using serialize (achieved through JS). Once I retrieve this data from the database I need to be able to unserialize it so that each piece of data can be used.
An example of the data serialized and stored is
[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]
The number of ID's stored in each serialized data varies and the JS plugin adds the [ and ] brackets around the serialization.
I have used http://www.unserialize.com/ to test an unserialization of the data and it proves successful using print_r. I have tried replicating this with the following code:
<?php
print_r(unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]'));
?>
but I get an error. I am guessing that I need to use something similar to strip_tags to remove the brackets, but am unsure. The error given is as follows
Notice: unserialize(): Error at offset 0 of 70 bytes
Once I have the unserialized data I need to be able to use each ID as a variable and I am assuming to do so I need to do something as:
<?php
$array = unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]');
foreach($array as $key => $val)
{
// Do something here, use each individial ID however
// e.g database insert using $val['id']; to get H592736029375 then K235098273598 and finally B039571208517
}
?>
Is anyone able to offer any help as to how to strip the serialized data correctly to have the ID's ready in an array to then be used in the foreach function?
Much appreciated.
PHP's serialize() and unserialize() functions are PHP specific, not for communicating with other languages.
It looks like your JS serialize function is actually generating JSON though, so on the PHP side, use json_decode() rather than unserialize.
Here's a fiddle
$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $index=>$data){
echo "$index) {$data['id']}\n";
}
Outputs:
0) H592736029375
1) K235098273598
2) B039571208517
I am still a beginner in PHP and MySQL and have come across a complicated array I need some help with.
So far the arrays I have worked with are fairly flat, i.e. 1 row of data with multiple fields, say for example a result based on a single address, so line1, line2, line3, town, etc.
I am now dealing with an external api that returns the following results in xml
{"result":
{
group1 [{"fieldname1":"fieldresult1", "fieldname2":"fieldresult2}]
group2 [{"fieldname3":"fieldresult3", "fieldname4":"fieldresult4}]
}
"message":"OK",
"success":true}
My question is how do I access each of the results,
I am planning on using a foreach statement, and will be calling the result $xmlarray.
I then want to define strings such as $field1, $field2, but not sure how to do this when it seems to be quite a deep array, I am guessing something like:
$field1 = $array([0]["field2"];
As I say, I need someones help just to give me a brief overview here, thanks
This content of you posted Data looks like JSON to me...
so you could try some like
$json = json_decode($array);
than you could go for
$field1 = $json['group1']['fieldname1'];
and so on.
source
This is not XML. It is json. Use json_decode() for this.
$data = json_decode($response); //$response is the response you are getting from the api.
var_dump($data);
$data will contain the response. The you can access them easily.json_decode()
Disclaimer: I am fairly new to using json.
I am trying to use php to receive json data from an iPAd application. I know how to convert json to an array in php, but how do I actually receive it and store it into a variable so it can be decoded?
Here are a couple examples that I have tried based on google and stackoverflow searches.
$json_request = #file_get_contents('php://input');
$array = json_decode($json_request);
AND ALSO
$array = json_decode($_POST['data'], true);
Any suggestions?
You have the basic idea already.
you should test that the value is set and also strip extra slashes from the incoming string before trying to parse it as JSON.
if(isset($_POST['data'])){
$array = json_decode(stripslashes($_POST['data']),true);
//$array now holds an associative array
}//Data Exists
It also would not be a bad idea before you start working with the array to test that the call to json_decode() was successful by ensuring that $array isn't null before use.
If you do not fully trust the integrity of the information being sent you should do extended checking along the way instead of trusting that a given key exists.
if($array){ // Or (!is_null($array)) Or (is_array($array)) could be used
//Process individual information here
//Without trust
if(isset($array['Firstname'])){
$CustomerId = $array['Firstname'];
}//Firstname exists
}//$array is valid
I in-particular like to verify information when I am building queries dynamically for information that may not be required for a successful db insert.
In the above example $_POST['data'] indicates that what ever called the PHP script did so passing the JSON string using the post method in a variable identified as data.
You could check more generically to allow flexibility in the sending method by using the $_REQUEST variable, or if you know it is coming as via the get method you can check $_GET. $_REQUEST holds all incoming parameters from both get and post.
If you don't know what the name of the variable coming in is and want to play really fast and loose you could loop over the keys in $_REQUEST trying to decode each one and use the one that successfully decoded (if any). [Note: I'm not encouraging this]