我试图寻找解决方案,但似乎无法理解我遇到的问题。
我有一个搜索查询,其中带有“ where子句”,说明用户输入的多个单词是否返回结果。
我需要以搜索到的相同顺序返回结果。
即使我只添加了“ ORDER BY DESC”,也会引发“试图获取非对象的属性”错误。
这是我的代码:
$word = $_GET['word'];
$word3 = $_GET['word'];
$word = explode(";", $word);
$noOfWords = count($word);
$word2 = $word3;
if ($noOfWords == 1) {
$searchString = " word_eng LIKE '" . $conn->escape_string($word3)
"%'";
} else {
$searchString = $whereClause = "";
foreach ($word as $entry) {
$searchString .= " OR word_eng LIKE '" . $conn->escape_string($entry) . "' ORDER BY '" . $word2 . "' ";
}
}
$whereClause = ($searchString != "") ? " WHERE " . preg_replace('/OR/',
'', $searchString, 1) : $whereClause;
$sql = "SELECT word_eng FROM words " . $whereClause . " LIMIT 17";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row1 = $row["word_eng"];
echo $row1;
}
答案 0 :(得分:0)
尝试使用ORDER BY的方式存在两个问题。任何SQL中只能有1个order by子句,您要为添加的每个单词添加该子句。第二部分是期望按列名排序,并按搜索词排序。
由于想要保持术语的顺序和结果的顺序,因此有必要使用带有case
之类的order by子句(Can you add an if statement in ORDER BY?可能有助于解释这一点)。
$orderBy = "";
if ($noOfWords == 1) {
$searchString = " word_eng LIKE '" . $conn->escape_string($word3) ."%'";
} else {
$searchString = $whereClause = "";
$orderBy = " order by case `word_eng` ";
foreach ($word as $order=>$entry) {
$searchString .= " OR word_eng LIKE '" . $conn->escape_string($entry) . "'";
$orderBy .= " when '$entry' then $order ";
}
$orderBy .= " end ";
}
$whereClause = ($searchString != "") ? " WHERE " . preg_replace('/OR/',
'', $searchString, 1) : $whereClause;
$sql = "SELECT word_eng FROM words " . $whereClause . " " .$orderBy." LIMIT 17";
答案 1 :(得分:0)
if ($noOfWords == 1) {
$searchString = " word_eng LIKE '" . $conn->escape_string($word3)
"%'";
} else {
$searchString = $whereClause = "";
foreach ($word as $entry) {
$searchString .= " OR word_eng LIKE '" . $conn->escape_string($entry);
}
$searchString .= "' ORDER BY '" . $word2 . "' ";
}
答案 2 :(得分:0)
我认为您搞砸了下面一行代码中的MySQL查询字符串。
$searchString .= " OR word_eng LIKE '" . $conn->escape_string($entry) . "' ORDER BY '" . $word2 . "' ";
您的查询正在生成
之类的内容ORDER BY DESC
“按订单查询”应该是这样的
ORDER BY expression [ ASC | DESC ];
因此您缺少查询中的表达式。