I want to parse following JSON object to perform mysql query.

$json_data = '{
"table":"login",
"operation":"insert",
"columns": [
{
  "valid": "yes",
  "deviceid": "gt456"
},
{
  "valid": "yes",
  "deviceid": "gt896"
}

],
"where":[
 { "username": "max" },
 { "username": "steve"}
 ]
}';

On parsing it will parse table, operation(insert/update/delete), columns affected by operations and where clause. How do i do it using PHP to execute desired sql query as per JSON input. Please help.

share|improve this question
2  
It's not exactly a trivial thing built in to PHP, you'll have to write your own parser. A good place to start would be the function json_decode to convert the JSON string to a PHP array. – Brandon Wamboldt Mar 11 at 12:19
json_decode is your friend. – j0k Mar 11 at 12:19
1  
Potentially it'll also be wide open to SQL injection. – Brian Mar 11 at 12:22
I have used json_deocde; but how do I write generic solution to suit any type of operation on any number of arguments and where clause? – sam Mar 11 at 12:23
Sounds like you get these from some external input source, but you don't mention such. Where are these come from? Maybe there's already a server side component for that. – complex857 Mar 11 at 12:24
show 1 more comment

closed as not a real question by j0k, Rikesh, Kevin B, NikiC, akond Mar 11 at 17:13

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, see the FAQ.

1 Answer

The whole idea seems like a testbed for skiddies for some SQL injection. If you still want to continue with it what I would suggest is you build a parser that does something like this (in pseudocode):

$query = "";
$operation = json[operation];
$table = json[table];

switch ($operation) {
  case 'insert':
    $data = // loop over array and create an assoc array of fields => values
    $query = "insert into $table values($data)" // populate from array
    break;
  case 'select':
    $data = loop over and create array of fields
    query = "select $data from $table" // populate from array
    break;
}

$whereclause = array(); // populate assoc array with json['where'] key=>values
$query .= "where " // populate from assoc array from earlier

echo $query;
share|improve this answer
Thanks. I will check it and let you know. – sam Mar 11 at 13:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.