我正在使用自动完成功能并且运行良好但是当我使用多行时,结果有时会在同一行...你能帮助我显示每行一个结果并且只有一个匹配结果(当时DB很多次重复)而不是3个或更多相同的单词...
这是一个向您展示问题的捕获:
我需要在数据库重复多次时只显示一个单词...我知道这可以通过“DISTINCT”解决但是当表中的多行时,我的代码中的代码不起作用。
这是我的代码:
<?php
$mysqli = new mysqli('localhost', 'cmedic', '21M1Sy', 'smedic');
$mysqli->set_charset("utf8");
$text = $mysqli->real_escape_string($_GET['term']);
$query = "SELECT diagnostico, diagnostico1, diagnostico2, diagnostico3, diagnostico4, diagnostico5, diagnostico6 FROM DIAGNOSTICO WHERE diagnostico LIKE '%$text%' OR diagnostico1 LIKE '%$text%' OR diagnostico2 LIKE '%$text%' OR diagnostico3 LIKE '%$text%' OR diagnostico4 LIKE '%$text%' OR diagnostico5 LIKE '%$text%' OR diagnostico6 LIKE '%$text%'";
$result = $mysqli->query($query);
$json = '[';
$first = true;
while($row = $result->fetch_assoc())
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['diagnostico'].''.$row['diagnostico1'].''.$row['diagnostico2'].''.$row['diagnostico3'].''.$row['diagnostico4'].''.$row['diagnostico5'].''.$row['diagnostico6'].'"}';
}
$json .= ']';
echo $json;
?>
这是脚本:
$('#auto').autocomplete({
source: "scripts/nostic.php",
minLength: 3
});
输入ID:
<input type="text" name="diagnostico1" id="auto"/>
答案 0 :(得分:1)
也许这就是你所需要的。它将所有diagnosticoN
列分成一列,然后使用UNION DISTINCT
过滤掉重复的内容。
$mysqli = new mysqli('localhost', 'cmedic', '21M1Sy', 'smedic');
$mysqli->set_charset("utf8");
$query = "SELECT diagnostico FROM DIAGNOSTICO WHERE diagnostico LIKE CONCAT('%', ?, '%')
UNION DISTINCT
SELECT diagnostico2 FROM DIAGNOSTICO WHERE diagnostico2 LIKE CONCAT('%', ?, '%')
UNION DISTINCT
SELECT diagnostico3 FROM DIAGNOSTICO WHERE diagnostico3 LIKE CONCAT('%', ?, '%')
UNION DISTINCT
SELECT diagnostico4 FROM DIAGNOSTICO WHERE diagnostico4 LIKE CONCAT('%', ?, '%')
UNION DISTINCT
SELECT diagnostico5 FROM DIAGNOSTICO WHERE diagnostico5 LIKE CONCAT('%', ?, '%')
UNION DISTINCT
SELECT diagnostico6 FROM DIAGNOSTICO WHERE diagnostico6 LIKE CONCAT('%', ?, '%')";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('ssssss', $_GET['term'], $_GET['term'], $_GET['term'], $_GET['term'], $_GET['term'], $_GET['term']);
$result = $stmt->execute();
$json = array();
$stmt->bind_result($diagnostico);
while ($stmt->fetch()) {
$json[] = array('value' => $diagnostico);
}
echo json_encode($json);
我还展示了如何使用参数化查询而不是插入字符串。