如何在PHP / MySQL中创建搜索功能

时间:2017-08-10 20:29:58

标签: php mysql

我写了这段代码:

<div class="container mx-auto">
    <!--Add class table-responsive for responsive table -->
    <div class="row">
        <div class="col-md-6">
            <form method="post">
            <div class="input-group">
                <input size='14' type="text" class="form-control" placeholder="Search for..." name="searchValue">
                <span class="input-group-btn">
                    <button class="btn btn-secondary" name='search' type="submit"><i class="fa fa-search"></i></button>
                </span>
            </div>
            </form>
        </div>
    </div>

    <table class="table mx-auto" id="'table">
        <thead>
        <tr>
            <th>Name</th>
            <th>Surname</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Company</th>
            <th>More</th>

        </tr>
        </thead>
        <tbody>
        <?php
        $pagination = new Pagination(7);

        $page_max = $pagination->getPageMax();



        $start = $pagination->getStart();

        if(!isset($_POST['search'])) {
            $numberOfPages = $pagination->numberOfPages($database->getData("SELECT count(id) FROM customers"));
            $customers = $database->getDataAsArray("SELECT * FROM customers LIMIT $start, $page_max");
        }
        else{
            $searchValue = '%'. $_POST['searchValue'] . '%'; 
            $numberOfPages = $pagination->numberOfPages($database->getData("SELECT count(id) FROM customers WHERE name LIKE '$searchValue' "));
            $customers = $database->getDataAsArray("SELECT * FROM customers WHERE name LIKE '$searchValue' LIMIT $start, $page_max");
        }


        foreach($customers as $customer){
            $name = $customer ['name'];
            $surname = $customer['surname'];
            $email = $customer['email'];
            $phone = $customer['phone'];
            $company = $customer['company'];
            $id = $customer['id'];
            echo "<tr>
                    <td>$name</td>
                    <td>$surname</td>
                    <td>$email</td>
                    <td>$phone</td>
                    <td>$company</td>
                    <td><a href='customerInfo.php?id=$id' class='btn btn-sm btn-info'><i class='fa fa-info'></i></a></td>



                  </tr>";
        }
        ?>
</tbody>
</table>
    <ul class="pagination">
        <?php

        echo $pagination->previous($numberOfPages);


        for($i = 0; $i < $numberOfPages; $i++){
            echo '<li class="page-item"><a class="page-link" href="?page='. $i . '">'. $i. '</a></li>';
        }

        echo $pagination->next($numberOfPages);
        ?>

    </ul>
</div>

我想在我的表中搜索,这个工作到目前为止工作正常但是当我在A上搜索并且我点击我的分页页面1时它会重建包含来自数据库的所有te记录的页面。

我尝试在按钮点击时向网址添加参数,但在创建带链接的按钮时,searchValue仍为空。

这个问题与我的sql查询无关。关于用分页搜索

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:-1)

使用$ _GET方法。或者Ajax。