A
A
arseniy882020-11-30 17:52:14
PHP
arseniy88, 2020-11-30 17:52:14

How to do PHP / RestAPI / RedBeanPHP filtering?

Hello !

I do filtering through get parameters (I use RedBeanPHP):

//sort
$sort = $_GET["_sort"];
//order
$order = $_GET["_order"];
//limit
$limit = $_GET["_limit"];
//search
$search = $_GET["q"];
//category
$category = explode(",", $_GET["category"]);
//min - max
$min = $_GET["min"];
$max = $_GET["max"];
//auth
$auth = explode(",", $_GET["auth"]);

$query = "";
$query .= isset($sort) && isset($order) ? "ORDER BY $sort $order " : "";
$query .= $limit !== 0 ? "LIMIT $limit " : "";
$query .= isset($search) ? "search_tags LIKE '%$search%'" : "";

if ($category[0] !== "") {
  foreach ($category as $categoryKey => $value) {
    if ($categoryKey === 0) {
      $query .= "category LIKE '%$value%' ";
    } else {
      $query .= "OR category LIKE '%$value%' ";
    }
  }
}

$query .= $min !== 0 && $max !== 0 ? "price >= $min AND price <= $max " : "";

if ($auth[0] !== "") {
  foreach ($auth as $authKey => $value) {
    if ($authKey === 0) {
      $query .= "auth LIKE '%$value%' ";
    } else {
      $query .= "OR auth LIKE '%$value%' ";
    }
  }
}

$goodsMV = R::findAll("goods", $query);


How not to fence a large number of if and correctly specify SQL, that is, OR, AND?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FanatPHP, 2020-11-30
@FanatPHP

Apologize to the customer, return the advance, buy a textbook or pay for decent courses, master the basics of programming, the basics of web programming, the basics of SQL, the basics of web application security, the basics of algorithms, the basics of working with a database from PHP, and only after that gradually proceed to this task.
Now this trash cannot be uploaded to production under any circumstances.

S
Slavik, 2020-11-30
@Makro_Slavik

Through $_GET["category"] pass the category id to collect in an array and instead of foreach ($category as $categoryKey => $value)
and category LIKE '%$value%' use the "in" operator there is such in sql - 2sql.ru /novosti/sql-in
get something like this
$query .= "WHERE category IN ($categories)";

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question