网站只能从数据库中搜索或排序数据
本文关键字:搜索 排序 数据 数据库 网站 | 更新日期: 2023-09-27 18:27:09
我已经为大学创建了一个基本的电子商务网站,我在排序和搜索我的产品表时遇到了问题,我的页面显示的产品很好。该网站是在visualstudio2012中制作的,使用带有C#的razorv2标记。
@{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "Store";
var db = Database.Open("StarterSite");
string sql = "";
switch (Request["sort"])
{
case "PriceASC":
sql = "SELECT * FROM Products order by Product_Price ASC";
break;
case "PriceDESC":
sql = "SELECT * FROM Products order by Product_Price DESC";
break;
default:
sql = "SELECT * FROM PRODUCTS ORDER BY Product_ID";
break;
}
if (Request["search"] != "")
{
sql = "SELECT * FROM Products where Product_Keywords like '%" + Request["search"] + "%'";
}
}
这是我正在使用的代码,它们都是独立工作的,但当我这样把它们放在一起时,无论哪一个是第二个,都会接管并破坏第一个。我已经多次交换它们来测试这一点,有什么想法可以让它们很好地协同工作吗?
当您将它们组合在一起时,它不再起作用的原因是因为您覆盖了在第一步中进行的查询。我要做的是把这个过程分解成几个部分。
//declare your variable. I added a connection and command so I can include parameters in the process.
string orderBy = "";
string whereClause = "";
string sql = "";
//create your order by clause
switch (Request["sort"])
{
case "PriceASC":
orderBy = "order by Product_Price ASC";
break;
case "PriceDESC":
orderBy = "order by Product_Price DESC";
break;
default:
orderBy = "ORDER BY Product_ID";
break;
}
//create your where clause.
if (!string.IsNullOrEmpty(Request["search"])) // forgot the ! here
{
whereClause = string.Format(" where Product_Keywords like '%{0}%'", Request["search"]); // very unsafe to plug this in. should use parameter
}
sql = string.Format("SELECT * FROM Products{0} {1}",whereClause, orderBy); //build your query string. if no search parameter was given the where clause will be blank, but the order by will still exist.
@foreach (var row in db.Query(sql))
{
//some code here
}