php - 在 PHP 中搜索 MySQL 数据库

标签 php mysql

我正在尝试创建一个搜索页面,允许用户从 mysql 数据库中键入书名的任何部分。使用此代码,无论输入什么单词,我都不会得到任何结果。目标是使用查询结果并使用 num_rows 来确定结果中的行数,并使用 fetch_assoc 方法将结果行作为关联数组获取。我没有收到任何错误。只是空白结果。

搜索书籍页面:

$page_title = "Search book";

include ('includes/header.php');
?>
<h2>Search Books by Title</h2>
<p>Enter one or more words in book title.</p>
<form action="searchbooksresults.php" method="get">
<input type="text" name="terms" size="40" required />&nbsp;&nbsp;
<input type="submit" name="Submit" id="Submit" value="Search Book" />
</form>
<?php

include ('includes/footer.php');
?>

搜索结果页面

$page_title = "Books in Our Store";
require 'includes/header.php';
require_once('includes/database.php');

//retrieve the search terms from a query string
$term_string = filter_input(INPUT_GET, "term", FILTER_SANITIZE_STRING);
$terms = explode(" ", $term_string);

//sql query statement
$sql = "SELECT * FROM books WHERE 1";
foreach ($terms as $term){
$sql .= "AND CONCAT(title) LIKE %" .$term. "%";
}
//execute the query
$query = $conn->query($sql);

//using the query results to dertmine number of rows
$results = @$conn->num_rows($query);


//Handle errors
if (!$query) {
$errno = $conn->errno;
$error = $conn->error;
$conn->close();
die("Selection failed: ($errno) $error.");
}
?>

<h2>Books: <?php $term ?></h2>
<table id="booklist" class="booklist">
    <tr>
    <th>Title</th>
    <th class="col2">Author</th>
    <th class="col3">Category</th>
    <th class="col4">Price</th>
    </tr>

<?php
while ($row = $query->fetch_assoc($results)) {
    echo "<tr>";
    echo "<td><a href='bookdetails.php?id=", $row['id'], "'>",     $row['title'], "</a></td>";
    echo "<td>", $row['author'], "</td>";
    echo "<td>", $row['category_id'], "</td>";
    echo "<td>", $row['price'], "</td>";
    echo "</tr>";
}
?>
</table>

<?php
require 'includes/footer.php';

最佳答案

尝试将 AND 替换为 OR,因为按照您现在使用它的方式,一行必须包含输入分隔符空间中的所有术语。还要添加单引号。

$sql .= "AND CONCAT(title) LIKE %" .$term. "%";

致:

$term_string = 'Term1 Term2 Term3';
$terms = explode(" ", preg_replace('/(\s)+/', ' ', trim($term_string))); //Remove multiple spaces

$sql = "SELECT * FROM books";
$temp = array();

foreach ($terms as $term){
    $temp[] = "title LIKE '%$term%'";
}
if (!empty($temp)) {
    $sql .= " WHERE ".implode(' OR ', $temp);
}

echo $sql;

结果:

SELECT * FROM books WHERE title LIKE '%Term1%' OR title LIKE '%Term2%' OR title LIKE '%Term3%'

此外,不要使用 @ 抑制错误。最后尝试使用准备好的语句。

关于php - 在 PHP 中搜索 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33620357/

相关文章:

php - 存储数据库信息以通过电子邮件发送

java - 后端生成 pdf 文件(标签、装箱单等) - 需要从浏览器自动打印到预先选择的打印机 - 解决方法?

php - 将字符串拆分为数字和文本,但接受内部包含单个数字的文本

php - PHP 或 MySQL 中的低优先级请求

MySQL:在我的用户表中查找重复的名称

php - 追加销售和关联产品选项卡错误 - 迁移后

java - 用 Java 构建基于用户输入的动态 SQL 查询

python - mysql - 如何确定存储可变字符串的字段的长度?

php - 用户友好的 URL 而不是查询字符串?

php - array_merge 或 array_splice 合并数组哪个更快?