如何在分页中添加搜索引擎

时间:2019-07-08 06:51:52

标签: php html css mysqli search-engine

我使用表来进行分页,但是我想在其中使用搜索引擎,如何在其中添加搜索引擎?我有一个简单的搜索表单,但不知道如何集成到其中。

<html>
<head>
<title>Search</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<form method="get" action="index.php">
<label>Search:     <input type="text" name="query"/>
 <input type="submit" name = "search" value="search" />
</form>
<?php
include('db.php');

if (isset($_GET['page_no']) && $_GET['page_no']!="") {
    $page_no = $_GET['page_no'];
    } else {
        $page_no = 1;
        }

    $total_records_per_page = 10;
    $offset = ($page_no-1) * $total_records_per_page;
    $previous_page = $page_no - 1;
    $next_page = $page_no + 1;
    $adjacents = "2"; 

    $result_count = mysqli_query($con,"SELECT COUNT(*) As total_records FROM `cases`");
    $total_records = mysqli_fetch_array($result_count);
    $total_records = $total_records['total_records'];
    $total_no_of_pages = ceil($total_records / $total_records_per_page);
    $second_last = $total_no_of_pages - 1; // total page minus 1

    $result = mysqli_query($con,"SELECT * FROM `cases` LIMIT $offset, $total_records_per_page");
    while($row = mysqli_fetch_array($result)){
        echo "<tr>
              <td>".$row['name']."</td>
              <td>".$row['email']."</td>
              <td>".$row['phone']."</td>
              <td>".$row['case']."</td>
              </tr>";
        }
    mysqli_close($con);
    ?>
</tbody>
</table>

1 个答案:

答案 0 :(得分:0)

您可以将搜索项添加到sql查询中:

<form method="get" action="index.php">
    <!-- Show query item after page reloading -->
    <label>Search: <input type="text" name="query" value="<?php echo htmlentities(isset($_GET['query']) ? $_GET['query'] : ''); ?>"/>
    <input type="submit" name = "search" value="search" />
</form>
<?php
include('db.php');

if (isset($_GET['page_no']) && $_GET['page_no']!="") {
    $page_no = $_GET['page_no'];
} else {
    $page_no = 1;
}

$where = '';
if (!empty($_GET['query'])) {
    //it is important to escape search item before query
    $query = mysqli_real_escape_string($con, $_GET['query']);
    //there are can be any conditions
    //lets say you want to find user by name
    $where = "WHERE cases.name = '{$query}'";
}

//items for pager need be calculated with query too
$result_count = mysqli_query($con,"SELECT COUNT(*) As total_records FROM `cases` {$where}");

$total_records = mysqli_fetch_array($result_count);
$total_records = $total_records['total_records'];
$total_no_of_pages = ceil($total_records / $total_records_per_page);
$second_last = $total_no_of_pages - 1; // total page minus 1

//add condition to data query
$result = mysqli_query($con,"SELECT * FROM `cases` {$where} LIMIT $offset, $total_records_per_page");

我建议您将PDOprepared statements结合使用,因为它们更紧凑,更安全。

也请看看laravelsymfony之类的现代框架,因为它们已经具有相同的功能。