我正在为该项目建立我的第一个网站。我有一个运动鞋数据库,该数据库已经与该站点连接,我显示了有关产品的信息,但是我想添加一些按钮,这些按钮可用于按价格或名称对数据库中的鞋子进行排序并显示在站点上。
我有列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;
}
?>
我希望数据会被排序,但没有任何变化
最佳答案
尝试使用此代码,它将按以下顺序使用多个顺序:
<?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;
}
?>
关于php - PHP使用ORDER BY查询MySQL使用按钮对数据库项进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56020109/