2017-08-10 47 views
0

我寫了這個代碼:如何在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> 

我想在我的表進行搜索,能正常工作,但迄今爲止,當我在搜索的例子,我點擊我的分頁它使用數據庫中的所有te記錄重建頁面。

我試圖添加一個參數到按鈕點擊時,但在創建此鏈接時,searchValue仍爲null。

這個問題不是關於我的sql查詢。這是關於搜索與分頁

任何人都可以幫我解決這個問題嗎?

+0

您需要着眼於使用AJAX,因此頁面不會刷新。那裏有很多的教程。但是,發生的事情是,您的頁面會完全重新加載並從頭開始運行腳本。 – Difster

+1

'$ searchValue'需要在您的SQL字符串中引用,或者更好的是,綁定到一個準備好的語句。另外,它可能應該包含一些通配符,以便與'LIKE'一起使用。 –

+0

對不起,我拿着那張重複的投票跳了槍,而且我已經收回了它。不過,我相信我之前的評論仍然是你應該解決的問題,不管它是否引起你在這裏問的問題。 –

回答

-1

使用$ _GET方法。或者Ajax。