我是新用户,我的搜索结果有问题。我目前正在建立一个搜索帖子功能的网站。它与mysql一起工作正常。然后我读到有关PHP将删除一些旧功能。所以我试图从mysql转换为mysqli,但我有很多错误。我不知道还能做什么,因为我从这里和谷歌尝试了很多建议,但它仍然无效。我的表(title, keywords)
中只有(search_table)
个字段。如果用户搜索任何'title'
。
'keywords'
我的表格:
<form name="search_form" action="search.php" method="post">
<input type="text" name="search_posts" placeholder="Search for posts" size="20" maxlength="50"/>
<input type="submit" name="submit" value="Search" />
</form>
我的工作mysql:
<?php
$host='localhost';
$mysql_username='root';
$mysql_password='';
$database='my_db';
$connection_error='<b>Unable to connect to the database!</b>';
if(!@mysql_connect( $host , $mysql_username , $mysql_password ) || !@mysql_select_db($database))
{
die ($connection_error);
}
$search = mysql_real_escape_string(trim($_POST['search_posts']));
$find_posts = mysql_query("SELECT * FROM `search_table` WHERE `keywords` LIKE '%$search%'") ;
$count = mysql_num_rows($find_posts);
if($count == 0){
echo 'There are no search result!';
} else {
while($row = mysql_fetch_assoc($find_posts))
{
$title = $row['title'];
$keywords = $row['keywords'];
echo "<a href='#'>$title</a> >>> $keywords<br />";
}
}
?>
转换mysqli(问题):
<?php
$host = 'localhost';
$mysql_username = 'root';
$mysql_password = '';
$my_database = 'my_db';
$mysqli = new mysqli($host,$mysql_username,$mysql_password,$my_database);
if($mysqli->connect_errno) {
printf("Connection to database failed: %s\n", $mysqli->connect_error);
exit();
}
$search_posts = $mysqli->real_escape_string(trim($_POST['search_posts']));
$find_posts = $mysqli->query("SELECT * FROM `search_table` WHERE `keywords`='?'") or die($mysqli->error.__LINE__);
if($count == 0) {
echo 'NO SEARCH RESULTS FOUND!';
}
else {
while($row = $find_posts->fetch_assoc())
{
$title = $row['title'];
$keywords = $row['keywords'];
echo "<a href='#'>$title</a> >>> $keywords<br />";
}
}
$mysqli->close();
?>
P / S:抱歉我的英语不好。我希望你们能帮助我或以简单的方式向我解释,因为我对这个领域没有太多的了解(自学 - 尝试和错误的东西^ _ ^)。如果你们有更好的解决方案,我将不胜感激,只要它能像旧的那样工作。提前谢谢。
答案 0 :(得分:0)
你做错了! MySQLi代码:
$search_posts = $_POST['search_posts'];
$find_posts = $mysqli->prepare("SELECT title, keywords FROM search_table WHERE keywords=?");
$find_posts->bind_param('s', $search_posts);
$find_posts->execute();
$find_posts->bind_result($title, $keywords);
$find_posts->store_result();
if($find_posts->num_rows > 0) {
while($find_posts->fetch()) {
echo "<a href='#'>$title</a> >>> $keywords<br />";
}
} else {
echo "No search results found!";
}
$find_posts->free_result();
$find_posts->close();
答案 1 :(得分:0)
当你把“?”在查询中,这就是你如何做“准备好的声明”。但是,(a)mysqli-&gt;查询函数不会执行预处理语句,它会执行简单的旧一次性语句。并且(b)即使它确实如此,你也永远不会将值绑定到“?”。因此,您正在搜索关键字等于文字问号的记录。
您可以像使用旧MySQL一样进行查询,以字符串形式构建参数:
$find_posts = $mysqli->query("SELECT * FROM `search_table`
WHERE keywords like '%$search_posts%'");
或者您可以将其作为准备好的声明:
$pq =$mysqli->prepare("SELECT * FROM `search_table`
WHERE keywords like ?");
$pq->bind_param('i', '%' . $search_posts . '%');
$pq->execute();
$find_posts=$pq->get_result();
另请注意,将测试从LIKE更改为=将改变您的结果。你可能不想这样做。