我正在为我的网站构建搜索功能,但是MySQl查询不会读取PHP变量,我并不是指错误,它似乎只是认为它们是NULL。
我目前的代码是:
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);
$sql = "SELECT * FROM Books";
if($_POST['find']!="")
{
if($_POST['field'] == "Books")
{
$sql = "SELECT *
FROM Books
JOIN bookauthor ON books.BookID = bookauthor.BookID
JOIN authors ON bookauthor.AuthorID = authors.AuthorID
WHERE books.BookName LIKE '%''".($_POST['find'])."''%'
GROUP BY books.BookName
ORDER BY authors.AuthorID";
}
else if ($_POST['field'] == "Authors")
{
$sql = "SELECT *
FROM Books
JOIN bookauthor ON books.BookID = bookauthor.BookID
JOIN authors ON bookauthor.AuthorID = authors.AuthorID
WHERE authors.Forename LIKE '%J.%'
AND authors.Surname LIKE '%%'
GROUP BY books.BookName
ORDER BY authors.AuthorID";
}
}
$result = mysql_query($sql, $conn) or die("Can't run query");
$loopnumber = 1;
if (mysql_num_rows($result) ==0 ){echo "No Results have been found";}
POST变量确实包含数据,因为我已经通过echo来测试它,但是我的网站只是给出了“没有找到结果”消息,这意味着查询没有返回任何结果。 即使我将POST传递给普通变量,我也会得到相同的结果。
但是,如果我删除“LIKE'%%'”并通过在网站上搜索输入来查找和完全匹配,它就可以正常工作。
编辑:嗯,刚刚完成,所以我将POST传递给变量,就像这样..
$searchf = "%".$_POST['find']."%";
并且在WHERE LIKE中使用该变量使其工作,现在我只是好奇为什么它不起作用。
我似乎太喜欢引号,应该去睡觉了。答案 0 :(得分:5)
首先,我猜你在尝试执行第一个查询时遇到MySQL语法错误。这一行:
WHERE books.BookName LIKE '%''".($_POST['find'])."''%'
应该是
WHERE books.BookName LIKE '%".$_POST['find']."%'
因为现在你正在
WHERE books.BookName LIKE '%''ABC''%'
什么时候你应该
WHERE books.BookName LIKE '%ABC%'
我不承认你理解你在使用第二个查询时所做的事情,第二个查询只是硬编码并且%%
是搜索条件之一,这实际上是毫无意义的。
答案 1 :(得分:0)
它在你的LIKE表达式中。如果在$ _POST ['find']中,则值为LOTR,查询将为 WHERE books.BookName LIKE'%''LOTR''%' 而且这次转发将是空的。只需删除双重'它应该可以工作。
答案 2 :(得分:0)
尝试这种方式:
$sql = "SELECT *
FROM Books
JOIN bookauthor ON books.BookID = bookauthor.BookID
JOIN authors ON bookauthor.AuthorID = authors.AuthorID
WHERE books.BookName LIKE '%".$_POST['find']."%'
GROUP BY books.BookName
ORDER BY authors.AuthorID";
应该是工作
答案 3 :(得分:0)
使用这个为我工作:
$query_casenumber = "SELECT * FROM pv_metrics WHERE casenumber='$keyword' OR age='$keyword' OR product='$keyword' OR eventpreferredterm='$keyword' OR patientoutcome='$keyword' OR eventsystemclassSOC='$keyword' OR asdeterminedlistedness='$keyword' OR narrative LIKE '%".$_POST['keyword']."%' ";