我有一个PHP网站来显示产品。我需要介绍一个'搜索'功能,可以在多个产品中找到关键字或短语。搜索PHP网站与MySQL数据库的脚本
我经历了一些现有的脚本,并写了/修改了一个虽然能够连接到数据库,但不返回任何值。调试模式会发出警告“mysqli_num_rows()
期望参数1为mysqli_result,布尔给定”。似乎我没有正确收集查询值。在PHP手册说,mysqli_query()
回报失败和成功的SELECT,SHOW FALSE,描述或解释查询mysqli_query()
会返回一个mysqli_result
对象和其他成功的查询mysqli_query()
将返回TRUE”。
有什么建议?
<form name="search" method="post" action="search.php">
<input type="text" name="searchterm" />
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="Search" />
</form>
<?php
$searchterm=trim($_POST['searchterm']);
$searching = $_POST['searching'];
$search = $_POST['search'];
//This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo 'Results';
//If they forget to enter a search term display an error
if (!$searchterm)
{
echo 'You forgot to enter a search term';
exit;
}
//Filter the user input
if (!get_magic_quotes_gpc())
$searchterm = addslashes($searchterm);
// Now connect to Database
@ $db = mysqli_connect('localhost','username','password','database');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to the database. Please try again later.';
exit;
}
else {
echo "Database connection successful."; //Check to see whether we have connected to database at all!
}
//Query the database
$query = "SELECT * FROM wp_posts WHERE post_title LIKE '%$searchterm%' OR post_excerpt LIKE '%$searchterm%' OR post_content LIKE '%$searchterm%'";
$result = mysqli_query($db, $query);
if (!$result)
echo "No result found";
$num_results = mysqli_num_rows($result);
echo "<p>Number of match found: ".$num_results."</p>";
foreach ($result as $searchResult) {
print_r($searchResult);
}
echo "You searched for $searchterm";
$result->free();
$db->close();
}
更正了@Rasclatt指出的错误代码。 – Manish 2014-09-27 11:35:30
那你有工作吗? – Rasclatt 2014-09-27 16:03:15
不,它没有。如上所述,似乎我无法在'mysqli_query()'函数中正确收集返回对象/值。 – Manish 2014-09-27 16:53:55