1

我写了一个搜索数据库的代码,但我不知道为什么当我搜索一些特定的关键字时,它会显示其他不相关的链接。这是代码和结果。

Page.Title = "Catalog Search";
var db = Database.Open("Shopping");
var searchWords = Request["searchTerm"].Split(' ');
IEnumerable<dynamic> result = Enumerable.Empty<string>();
var sqlSelect = "SELECT ProductId, ProductTitle FROM Products WHERE " +
"ProductTitle LIKE @0";
foreach(var word in searchWords)
{
result = result.Concat(db.Query(sqlSelect, "%" + word + "%").ToList());
}

所以我搜索了“Samsung LCD”,结果如下。

Samsung - 15" Series 9 Ultrabook Laptop
Samsung - Galaxy Tab 2 7.0
Samsung - 32" Class - LCD
Samsung - 32" Class - LCD 

我已经看到了一个正是我想要的 php 代码,但不幸的是我不知道如何转换它。这是php代码。

$searchTerms = explode(' ', $bucketsearch);
$searchTermBits = array();
foreach ($searchTerms as $term) {
    $term = trim($term);
    if (!empty($term)) {
        $searchTermBits[] = "bucketname LIKE '%$term%'";
    }
}

...

$result = mysql_query("SELECT * FROM buckets WHERE ".implode(' AND ', $searchTermBits).");

以及 php 搜索代码的结果。

SELECT * FROM buckets WHERE bucketname LIKE '%apple%' AND bucketname LIKE '%and%' AND bucketname LIKE '%pear%'
4

1 回答 1

0

我冒昧地添加了一些空检查等,但 C# 的代码看起来很像这样:

// make sure search terms are passed in, and remove blank entries
var searchTerms = Request["searchTerms"] == null ? 
                    new string[] {} : 
                    Request["searchTerms"].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

// build the list of query items using parameterization
var searchTermBits = new List<string>();
for (var i=0; i<searchTerms.Length; i++) {
    searchTermBits.Add("bucketname LIKE @" + i);
}

// create your sql command using a join over the array
var query = "SELECT * FROM buckets";
if (searchTerms.Length > 0) {
  query += " WHERE " + string.Join(" AND ", searchTermBits);  
} 

// ask the database using a lambda to add the %
var db = Database.Open("StarterSite");
var results = db.Query(query, searchTerms.Select(x => "%" + x + "%").ToArray());

// enjoy!
Response.Write(results.Count());

如果您遇到更多麻烦,请告诉我!

于 2012-08-11T09:13:32.427 回答