我有一个包含多个搜索字段的表单。其中一个是关键字。 在结果页面中,我想构建一个允许以任何顺序获得多个单词的查询(即" word1"," word2"," word3&#34 ; OR" word3"," word1"," word2"等)。 我知道我应该使用阵列,我已经尝试过,但我还没有解决它! 在我的代码下面。
谢谢!
<?php
$dbcnx = @mysql_connect('xxx', 'xxx', 'xxx');
if (!$dbcnx) {
exit('<p>Non posso connettermi al database.</p>');
}
if (!@mysql_select_db('xxx')) {
exit('<p>Non posso connettermi al database.</p>');
}
// The basic SELECT statement
$select = 'SELECT DISTINCT id_articolo, titolo, testo_articolo, data_articolo, categoria_id, abstract_articolo, id_categoria, categoria, link_categoria';
$from = ' FROM Articoli, Categoria';
$where = ' WHERE 1=1 AND categoria_id=id_categoria';
$order = ' ORDER BY data_articolo DESC';
$aid = $_POST['aid'];
if ($aid != '') { // An author is selected
$where .= " AND id_autore='$aid'";
}
// HERE I'D LIKE TO OBTAIN A QUERY USING MULTIPLE WORDS IN ANY ORDER
$searchtext = $_POST['searchtext'];
if ($searchtext != '') { // Some search text was specified
$where .= " AND testo_articolo LIKE '%$searchtext%'";
}
$results = @mysql_query($select . $from . $where . $order);
if (!$results) {
echo '</table>';
exit('<p>Error retrieving results from database!<br />'.
'Error: ' . mysql_error() . '</p>');
}
while ($result = mysql_fetch_array($results)) {
echo "<tr valign='top'>\n";
$id = $result['id_articolo'];
$resulttext = htmlspecialchars($result['testo_articolo']);
$titolo = $result['titolo'];
$cat = htmlspecialchars($result['categoria']);
$link_cat = htmlspecialchars($result['link_categoria']);
$abstract = accorcia($result['abstract_articolo']);
$data = convertiDataSql($result['data_articolo']);
echo "<tr bgcolor=$color><td><a href='aticolo.php?recordID=$id'><strong style='text-transform:uppercase' class='CapitalizeSmall'>$titolo</strong></a><div style='padding-left:8px'><em>$abstract</em></div><span align='center' style='padding-left:8px' class='generale'><strong>Inserito il $data</strong> | Categoria: <a href='$link_cat' class='stile26'>$cat<a/></span><br /><br /></td></tr>\n";
}
?>
答案 0 :(得分:2)
您不能使用您的查询构造。你正在建设
... field LIKE '%foo bar baz%'
将按顺序搜索文字文本foo bar baz
。
如果你想要“任何”订单,你将不得不按下文字:
... field LIKE '%foo%' AND field LIKE '%bar%' AND field LIKE '%baz%'
对于这类事情,您最好切换到全文索引并使用match against
代替。它专为这种搜索而设计,其中LIKE '%...%'
非常低效。
另外,你很容易受到sql injection attacks的攻击。</ p>