0

我是 Mysql Php 的初学者。我想制作一个搜索框,它可以找到包含在 mysql 中搜索表的多个单词的行。我通过互联网获得了一个脚本,如下所示。当我输入多个单词时,它会显示搜索单词最少的行。但我希望它只显示搜索多个单词的行。请帮我。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang='en'>
<head>
<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=UTF-8'/>
<title>Page title</title>
<style type="text/css">
table {
border-collapse: collapse;
border: solid 1px black;
}
td {
padding: 2px 6px;
border: solid 1px black;
}
</style>
</head>
<body>
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'>
<p>Search for: <input type='text' name='search' size='20'
maxlength='64'></p>
<p><input type='submit' value='Search'></p>
</form>
<?php
if(isset($_POST['search']))
{
$connx = mysql_connect('localhost', '*****', '*****') or
die("connx");
$db = mysql_select_db('test') or die(mysql_error());
# convert to upper case, trim it, and replace spaces with "|":
$search = (ini_get('magic_quotes_gpc')) ?
stripslashes($_POST['search']) :
$_POST['search'];
$search = mysql_real_escape_string($search);
$search = strtoupper(preg_replace('/\s+/', '|',
trim($_POST['search'])));
# create a MySQL REGEXP for the search:
$regexp = "REGEXP '[[:<:]]($search)[[:>:]]'";
$query = "SELECT * FROM `users` WHERE UPPER(`description`) $regexp
OR ".
"`name` $regexp";
$result = mysql_query($query) or die($query . " - " .
mysql_error());
echo "<table>\n";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
foreach($row as $key => $value)
{
echo "<td>$value</td>";
}
echo "</tr>\n";
}
}
?>
</body>
</html>
4

2 回答 2

5

这是一个选项:

$search = explode(" ", $_POST['search']);
$description = "";
$name = "";
foreach($search AS $s)
{
    $description .= "`description` LIKE '%".mysql_real_escape_string($s)."%' AND ";
    $name .= "`name` LIKE '%".mysql_real_escape_string($s)."%' AND ";
}

$description = substr($description, 0, -4);
$name = substr($name, 0, -4);

$query = "SELECT * FROM `users` WHERE ($description) OR ($name)";

如果您的搜索词类似于“Doctor John”,您的查询将如下所示:

SELECT * FROM `users` WHERE (`description` LIKE '%Doctor%' AND `description` LIKE '%John%') OR (`name` LIKE '%Doctor%' AND `name` LIKE '%John%')

这显然使这两个词成为描述或名称字段中的要求。这和你要找的一样吗?

PS - 查看 PHP 的PDO 库。mysql_ 函数太老了,不能再被视为标准了。他们会工作,但你应该升级。

于 2012-08-25T03:21:09.380 回答
0

我不完全确定你想说什么,但我认为你想要的是:

$words = explode(" ", $_POST["search"]);
$sql = "SELECT * FROM `users` WHERE ";
$where = array();
foreach ($words as $word) {
    $where[] = "UPPER(`description`) LIKE '%".mysql_real_escape_string($word)."%'";
}
$sql .= implode(" OR ", $where);
$result = mysql_query($sql);
于 2012-08-25T03:20:00.003 回答