0

In my php file I get string which looks like [["category_id","=","3"],["price","<","40"]] from Android. I will use that for select query. But how can I get each item from it? Here my code:

<?php
$filter = $_POST[‘filter’];
$filter_text = “”;
     foreach($filter as $filter_item){
        foreach($filter_item as list($column, $equality, $value)){
            $filter_text .= "product." . $column . $equality. "'" . $value . "' AND ";
        }
    }
...
?>
FDK
  • 43
  • 6
  • Could you print_r($_POST[‘filter’]) and add the output to your question? – Luckylazuli Nov 10 '20 at 12:44
  • 2
    What do you get with the current code? Any error? You mention that what you get from android is a string, have you tried to verify that `$filter` is not still a string? Also beware of your quotes: `‘` is not `'` and `“` is not `"` – Kaddath Nov 10 '20 at 12:46
  • The string is in JSON format, so you just need to use `json_decode($filter, true);` to convert it to an array. – Matt Nov 10 '20 at 12:55
  • 1
    Also it looks like you're building an SQL query there, you ought to use prepared statements to avoid SQL injection rather than concatenating vars into it from untrusted sources: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Matt Nov 10 '20 at 12:56

2 Answers2

0

You can use implode and some looping

$filter = isset($_POST['filter']) ? $_POST['filter'] : '';
$arr = json_decode($filter,true);

foreach($arr as $k => $v) {
  $query['q'][] = [
   'column' => 'product.' . $v[0],
   'equality' => $v[1],
   'value' => $v[2]
  ];
}

$filter = array();

foreach($query as $q) {
  foreach($q as $k) {

  $filter[]= sprintf("%s %s %s", $k['column'],$k['equality'],$k['value']);
    
  }
}

$query = implode(' AND ',$filter);

echo $query;
// product.category_id = 3 AND product.price < 40

Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Escaping is not enough! -Dharman

Jerson
  • 1,700
  • 2
  • 10
  • 14
  • If I assign $arr manually then code works, but if I get value with post then code doesnt work and print anything. I dont know PHP so much, so thanks for your warning, I will research it. – FDK Nov 10 '20 at 19:09
0

Looks like you're constructing a WHERE clause to an SQL query. Here's a clue on how to build the string, but you should be using prepared statements instead of injecting user input directly into your query! Also, you don't actually need to nest a foreach, as is demonstrated below. See comments for explanation.

To use prepared statements (and please do!), you can substitute the variables in the ANDed conditions with "product.? ? ?";. Then use PDOStatement::bindValue(). Other flavors of parameter binding are available.

<?php
    
// Your input array.
$filters = [["category_id","=","3"],["price","<","40"]];

// Your question is unclear on this, but if your $_POST['filter'] is not actually an array, but a JSON string, then you may try this:
$filters = json_decode($_POST['filter'], TRUE); // TRUE to decode to associative array.

// $where holds each WHERE condition, so you can perform a clean string glue with implode().
// In your current string concatenation, additional conditions are required, or the query
// will fail due to an errant trailing AND if none are following.
$where = [];

// $filterText will hold this part of your WHERE clause. Consider renaming it to something
// more descriptive, like $whereSql.
$filterText = '';
foreach ($filters as [$key, $comparisonOperator, $value])
        $where[] = "product.$key $comparisonOperator $value";

// Glue each condition with as many ANDs are necessary. 
$filterText .= implode(' AND ', $where);

echo $filterText;
// Outputs: product.category_id = 3 AND product.price < 40

UPDATE: Your question is a little unclear on this, so I've added something that you can try. This updated answer now assumes your input isn't actually an array, but a JSON string.

Ro Achterberg
  • 2,504
  • 2
  • 17
  • 17
  • Thanks for your answer. Same result with Jerson answer. If I assign $filters manually code works, but if I get value with post code doesnt work and print anything. I dont know PHP so much, I will research prepared statements. – FDK Nov 10 '20 at 19:13
  • Show me `var_dump($_POST['filter']);` and maybe I can update my answer to something more useful to you. – Ro Achterberg Nov 10 '20 at 19:15
  • It print nothing. But only $_POST['filter'] print [["category_id","=","3"],["price","<","40"]] – FDK Nov 10 '20 at 19:33
  • Try my update and see if this works. While `var_dump()` should _always_ produce some output, your comment just now tells me you might be dealing with a JSON string. – Ro Achterberg Nov 10 '20 at 19:51
  • Data is sent with string from android, but your update works. Thanks a lot – FDK Nov 11 '20 at 18:10