build SQL statement from json encoded string php - php

Welcome Stackoverflow nation ! I'm trying to decode json encoded string into SQL statement withing php.
Lets say I've such a json encoded string =>
$j = '{"groupOp":"AND","rules":[{"field":"id","op":"cn","data":"A"},{"field":"i_name","op":"cn","data":"B"}]}';
I want to build SQL WHERE clause (needed for filterToolbar search in jqGrid), something like this => "WHERE id LIKE %A% AND i_name LIKE %B% " and etc.
I've done this =>
$d = json_decode($j);
$filterArray = get_object_vars($d); // makes array
foreach($filterArray as $m_arr_name => $m_arr_key){
// here I can't made up my mind how to continue build SQL statement which I've mentioned above
}
Any ideas how to do that , thanks preliminarily :)

The first problem is you will want to pull out the groupOp operator.
Then, you have an object and inside that you have an array of objects, so you may want to look at the results of filterArray as that won't have the value you want.
Then, when you loop through, you will want to do it with an index so you can just pull the values out in order.
You may want to look at this question to see how you can get data out of the array:
json decode in php
And here is another question that may be helpful for you:
How to decode a JSON String with several objects in PHP?

There is an answer with an implementation for the server-side php code here
Correction: I had to unescape double-quotes in the 'filters' parameter to get it working:
$filters = str_replace('\"','"' ,$_POST['filters']);

Related

Getting value from string by index

I have a string of data formatted like so:
[{"pr_a_w":"10","pr_a_we":"10","pr_c_w":"10","pr_c_we":"10"},{"pr_a_w":"20","pr_a_we":"20","pr_c_w":"20","pr_c_we":"20"},{"pr_a_w":"111","pr_a_we":"11","pr_c_w":"111","pr_c_we":"111"}]
The string doesn't have any index/numbers like a regular array would and I'm finding it difficult to extract individual values e.g. with a regular array I could use:
$string[0]["pr_a_w"]
To get the first instance of "pr_a_w" and I could use:
$string[1]["pr_a_w"]
To get the second instance etc.
Is it possible to get single values from this string based on their number?
What you have there is valid JSON (serialized array of objects), so you could use json_decode to translate the serialized data into a native PHP array:
$array = json_decode('[{"pr_a_w":"10","pr_a_we":"10","pr_c_w":"10","pr_c_we":"10"},{"pr_a_w":"20","pr_a_we":"20","pr_c_w":"20","pr_c_we":"20"},{"pr_a_w":"111","pr_a_we":"11","pr_c_w":"111","pr_c_we":"111"}]',true);
$array will then allow you to do exactly what you stated you'd like to do above.
$array[0]["pr_a_w"]; // will give you 10
$array[1]["pr_a_w"]; // will give you 10
Try like this, No need to access with array index. You will get error if you access wrong index.
$json_arr= json_decode('[{"pr_a_w":"10","pr_a_we":"10","pr_c_w":"10","pr_c_we":"10"},{"pr_a_w":"20","pr_a_we":"20","pr_c_w":"20","pr_c_we":"20"},{"pr_a_w":"111","pr_a_we":"11","pr_c_w":"111","pr_c_we":"111"}]',true);
foreach($json_arr as $row){
echo $row['pr_a_w']."<br>";
}

PHP json_encode multiple arrays into one object

I am trying to return multiple arrays in one JSON object and having some difficulty with the syntax. An Android app receives updates from multiple tables, that I wish to be returned in one response.
Currently, this is how I am encoding the various result sets:
$json=json_encode(array($table1, $table2, $table3, $table4, $table5, $table6));
The data is returned in this format:
[{"table1":[{...}]},{"table2":[{...}]},...]
In the Android code, I'd like to be able to parse it as a JSONObject, from which I can then retrieve each array by name instead of parsing it as a JSONArray and retrieving each sub array by position. The JSON response would look like this instead:
{{"table1":[{...}]},{"table2":[{...}]},...}
It seems all I need to do is wrap the results arrays in an object, instead of an array on the PHP side, but although I've managed to blindly cobble together enough PHP code to get this far, I can't seem to figure out that final step.
Your last example is not valid JSON, curly braces always mean object with keys; instead you're treating it as an array. If you want an object, then add keys to the array in PHP like so:
$json=json_encode(array('a' => $table1, 'b' => $table2, 'c' => $table3));
This would then yield
{"a":{"table1":[{...}]},"b":{"table2":[{...}]},...}
Which seems to be what you want.
#Anonymous answer did the trick. Just to clarify, I had to clean up what I was doing previously, so instead of this:
$table1['table1'] =$stmt_table1->fetchAll(PDO::FETCH_ASSOC);
$table2['table2'] =$stmt_table2->fetchAll(PDO::FETCH_ASSOC);
...
$json=json_encode(array($table1, $table2, $table3, $table4, $table5, $table6));
I now have this:
$table1_results =$stmt_table1->fetchAll(PDO::FETCH_ASSOC);
$table2_results =$stmt_table2->fetchAll(PDO::FETCH_ASSOC);
...
$json=json_encode(array('table1' => $table1_results , 'table2' => $table2_results,...);

How to merge some static data with json encode mysql array data?

I am trying to merge a static data with json encode array data for output. Here is my php code:
$arr = array();
$rs = mysql_query("SELECT id, name, picture, mail, gender, birthday FROM users WHERE id='$logged_id' ");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":'.json_encode($arr).'}';
Now I want to merge other data with it:
$user_ip = array("user_ip" => $user_ip_address);
I have tried array_merge($arr, $user_ip). But it didn't work. I think this is not correct json array format if I merge with existing data array. Please let me know what to do how to output other data as well as current data coming from mysql with json encode.
I am getting such output with my existing code, which is correct:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11"}]}
But now I want to add other variable e.g $user_ip_address as user's data joining with current output data like this:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11",user_ip:"127.0.0.1"}]}.
I want to get it in this way. How to do it? Please let me know. Thanks in advance.
try this:
echo json_encode(array('users' => $arr, 'user_ip' => $user_ip_address));
on a side note:
you should use PHP PDO class to connect and query the database.
mysql_fetch_object returns an object, not an array. So, what are you doing by $arr[] = $obj; is just adding an object into an array. So, the actual structure of the $arr is something like
$arr => [
[0] => Object(....),
[1] => Object(....),
....
]
In your particular case, I assume you are fetching single row by primary key, so there are only one object.
THe simpliest way to fix this is to add a field to an object. I haven't worked with PHP since 5.3, so can't be sure, but it's as simple as adding
$obj->user_ip = $user_ip_address;
inside the loop.
Btw, a couple of questions for you:
Why do you use loop if it should result in a single row?
Why you are embedding the variable directly into SQL query. It's quite vulnerable, read about sql-injections and how to prevent it (one day I was really tired telling people here on SO to use PDO and prepared statements, so just go read about it),
Have you read the documentation about mysql_fetch_object and array_merge? Why not (because if you have read it you wouldn't be asking the question).
Tried debugging? E.g. attaching a debugger and watching for variables contents? Inserting logging or (God forgive me) debug print with echo?
"Didn't work" is a quite bad error description. This time you was lucky, because the error was obvious. Next time, please, be more specific.

PHP multidimensional array to JSON

So im trying to figure out the best way to get MySql table data into either a multidimensional PHP array or convert that multidimensional array into a json string.
Essentially what im trying to do is have a php include that returns the JSON string so i can iterate through it. I am needing a single key with multiple values, so im not 100% sure that im headed in the right direction.
I want to assign multiple values to the same key, for example:
[{"key1": "package1", "package2", "package3"}, {"key2": "package1", "package2", "package3", "package4"}]
I think that is not going to work right? Because i dont have any type of index's?
That is not valid JSON. The structure you are looking for would be something like:
[
{"key1": ["package1", "package2", "package3"]},
{"key2": ["package1", "package2", "package3", "package4"}]
^ An array as the value to the key "key1", "key2", etc..
]
At the PHP side, you would need something like:
For every row fetched from MySQL
$arr[$key] = <new array>
for each package:
append package to $arr[$key]
echo out json_encode($arr)
JS arrays have an implicit array keying, starting at index 0. What you've got is a perfectly valid JS array, the equivalent of having written:
var x = []; // create new empty array
x[0] = {"key1": .... }; // first object
x[1] = {"key2": ....} // second object
Note that the contents of your {} sub-objects is NOT valid.
You should never EVER built a JSON string by hand. It's too unreliable and easy to mess up. It's just easier to use a native data structure (php arrays/objects), then json_encode() them. Ditto on the other end of the process - don't decode the string manually. Convert to a native data structure (e.g. json_decode(), JSON.parse()) and then deal with the native structure directly.
essentially, JSON is a transmission format, not a manipulation format.

Getting array param out of query string with PHP

(NOTE: This is a follow up to a previous question, How to pass an array within a query string?, where I asked about standard methods for passing arrays within query strings.)
I now have some PHP code that needs to consume the said query string- What kind of query string array formats does PHP recognize, and do I have to do anything special to retrieve the array?
The following doesn't seem to work:
Query string:
?formparts=[a,b,c]
PHP:
$myarray = $_GET["formparts"];
echo gettype($myarray)
result:
string
Your query string should rather look like this:
?formparts[]=a&formparts[]=b&formparts[]=c
If you're dealing with a query string, you are looking at the $_GET variable. This will contain everything after the ? in your previous question.
So what you will have to do is pretty much the opposite of the other question.
$products = array();
// ... Add some checking of $_GET to make sure it is sane
....
// then assign..
$products = explode(',', $_GET['pname']);
and so on for each variable. I must give you a full warning here, you MUST check what comes through the $_GET variable to make sure it is sane. Otherwise you risk having your site compromised.

Categories