PHP сортировка элементов базы данных с помощью запроса ORDER BY MySQL с помощью кнопки - PullRequest
0 голосов
/ 07 мая 2019

Я делаю свой первый сайт для проекта.У меня есть база кроссовок, которая уже связана с сайтом, я отображал информацию о товарах, но хочу добавить кнопки, которые можно использовать для сортировки обуви в базе данных по цене или по названию и отображения на сайте.

У меня есть столбцы id, имя модели, цена и т. Д. Я взял приведенный ниже код и изменил его для использования в своем проекте, однако есть ошибка.В чем проблема?

index.php:

<h3>Sorting</h3>
                <div class="list-group-item checkbox">
                    <label><input type="checkbox" class="common_selector pricehilo" id="pricehilo" >Price (Highest-Lowest)</label></br>
                    <label><input type="checkbox" class="common_selector pricelohi" id="pricelohi" >Price (Lowest-Highest)</label></br>
                    <label><input type="checkbox" class="common_selector name" id="name" >Alphabetical</label>
                </div>

fetch_data.php:

<?php
include('database_connection.php');
if(isset($_POST["action"]))
{
 $query = "
  SELECT * FROM shoes 
 ";
if(isset($_GET["pricehilo"]))
 {
  $query .= "
   AND ORDER BY price DESC
  ";
 }
if(isset($_GET["pricelohi"]))
 {
  $query .= "
   AND ORDER BY price ASC
  ";
 }
if(isset($_GET["name"]))
 {
  $query .= "
   AND ORDER BY model_name
  ";
 }
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $total_row = $statement->rowCount();
 $output = '';
 if($total_row > 0)
 {
  foreach($result as $row)
  {
   $output .= '
   <div class="col-sm-4 col-lg-3 col-md-3">
    <div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px; height:300px;">
     <p align="center"><strong><a href="#">'. $row['model_name'] .'</a></strong></p>
     <img src="images/'. $row['image'] .'" alt="" class="img-responsive" >
     <h4 style="text-align:center;" class="text-danger" >'. $row['price'] .'</h4>
     <p>Color : '. $row['color'].' <br />
     Brand : '. $row['brand'] .' <br />
    </div>
   </div>
   ';
  }
 }
 else
 {
  $output = '<h3>No Data Found</h3>';
 }
 echo $output;
}
?>

IОжидается, что данные будут отсортированы, но ничего не изменится

1 Ответ

0 голосов
/ 09 мая 2019

Попробуйте с этим кодом, он будет работать с несколькими заказами по:

<?php
include 'database_connection.php';
if (isset($_POST["action"])) {
    $query = "SELECT * FROM shoes";
    $order_by_clause = [];
    if (isset($_GET["pricehilo"])) {
        $order_by_clause[]= "price DESC";
    }
    if (isset($_GET["pricelohi"])) {
        $order_by_clause[]= "price ASC";
    }
    if (isset($_GET["name"])) {
        $order_by_clause[]= "model_name";
    }
    if (!empty($order_by_clause)) {
      $query .= ' ORDER BY ' . implode(', ', $order_by_clause);
    }
    // echo $query;exit;
    $statement = $connect->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    $total_row = $statement->rowCount();
    $output = '';
    if ($total_row > 0) {
        foreach ($result as $row) {
            $output .= '
              <div class="col-sm-4 col-lg-3 col-md-3">
                <div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px; height:300px;">
                  <p align="center"><strong><a href="#">' . $row['model_name'] . '</a></strong></p>
                  <img src="images/' . $row['image'] . '" alt="" class="img-responsive" >
                  <h4 style="text-align:center;" class="text-danger" >' . $row['price'] . '</h4>
                  <p>Color : ' . $row['color'] . ' <br /> Brand : ' . $row['brand'] . ' <br />
                </div>
              </div>';
        }
    } else {
        $output = '<h3>No Data Found</h3>';
    }
    echo $output;
}
?>
...