我目前使用LIKE进行SQL搜索查询。然后,这将用于生成HTML格式的返回结果。
但是,如果它包含多个关键字,我想只返回一次,可能是第一行。目前,它会为关键字x返回一次项目,对关键字y再次返回。
目前我正在使用for和while循环来执行每个关键字的搜索。 这是最好的解决方法吗?还是有其他方法可以做到这一点?
目前我想保持简单,所以没有solr或lucene等等。
为了清晰起见,我添加了代码,但是大量代码并非无关紧要。代码可以工作,所以不在这方面寻找建议。
<?php
session_start();
include_once('connect_to_sql.php');
include_once('distance.php');
$itemList = '';
if(isset($_POST['words'])){
$words = $_POST['words'];
} else {
$words = "";
}
$queries = preg_split("/[\s,]+/", $words);
for($i = 0; $i < count($queries); $i++){
$keyword = $queries[$i];
if($keyword!=""){
if(isset($_SESSION['myLong']) && isset($_SESSION['myLat'])){
$request_long = $_SESSION['myLong'];
$request_lat = $_SESSION['myLat'];
$itemQuery = mysql_query("SELECT *, ( 3959 * acos( cos( radians('$request_lat') ) *
cos( radians( item_lat ) ) *
cos( radians( item_long ) -
radians('$request_long') ) +
sin( radians('$request_lat') ) *
sin( radians( item_lat ) ) ) )
AS distance FROM offerings WHERE sold = 'no' AND item_desc LIKE '%$keyword%'
ORDER BY distance ASC");
} else {
$itemQuery = mysql_query("SELECT * FROM offerings WHERE sold = 'no' AND item_desc LIKE '%$keyword%'
ORDER BY id DESC");
}
//get all items
if(mysql_num_rows($itemQuery) < 1){
$itemList = "No items currently on sale.";
} else {
while($itemResult = mysql_fetch_array($itemQuery)){
$from = $itemResult['from_user'];
$locationQuery = mysql_query("SELECT postcode FROM users WHERE id = '$from' ");
$locationResult = mysql_fetch_array($locationQuery);
$se = urlencode($locationResult['postcode']);
$num = urlencode($itemResult['id']);
if($itemResult['item_picture'] == ''){
$img = '<img src="../offerings/placehold.png" />';
} else {
$img = '<img src="../offerings/'.$itemResult['from_user'].'/'.$itemResult['item_picture'].'" />';
}
$url = "http://maps.google.com/maps/api/geocode/json?address=".$se."&sensor=false";
$jsonData = file_get_contents($url);
$data = json_decode($jsonData);
$xlat = $data->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$xlong = $data->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
if(isset($request_lat) && isset($request_long)){
$dist = number_format(distance($request_lat, $request_long, $itemResult['item_lat'], $itemResult['item_long']), 2)." miles / ";
$distkm = number_format(distance($request_lat, $request_long, $itemResult['item_lat'], $itemResult['item_long'])*1.609344, 2)." km";
} else {
$dist = $locationResult['postcode'];
$distkm = '';
}
$checkifsold = mysql_query("SELECT * FROM orders WHERE item_id='$num'");
if(mysql_num_rows($checkifsold) > 0){
$itemPrice = "SOLD";
} else {
$itemPrice = '£'.$itemResult['item_price'];
}
$itemList .= '<div class="anItemSearched"><a href="item.php?num='.$num.'">'.$img.'</a>
<div class="innerDetail">'.$dist.$distkm.'</div>
<div class="innerDetail">'.$itemPrice.'</div>
<div class="innerDetail">'.$itemResult['item_name'].'</div>
</div>';
}
}
}
}
echo $itemList;
?>
谢谢, Cillian