2015-09-07 88 views
-1

我想在php中創建一個搜索功能,它獲取輸入的值並在db中搜索它。 我有這樣的代碼:搜索功能php和mysql查看當前頁面的結果

<center><form method="post" id="search" action="search.php?go"> 

     <p> 

      <input type="text" name="name" id="name" /> 

      <input type="submit" id="search_btn" name="submit" value="Cerca utente" /> 
     </p> 

    </form></center> 

,並在php文件我已創建這樣的:

public function searchUser($nomeUtente) 
    { 

     $sql = "SELECT uUsername FROM users WHERE='$nomeUtente' "; 

     if(!$this->stmt = $this->mysqli->prepare($sql)) 
      throw new Exception("MySQL Prepare statement failed: ".$this->mysqli->error); 

     $this->stmt->execute(); 
     $this->stmt->store_result(); 
     $this->stmt->bind_result($nome); 
     if($this->stmt->num_rows == 0) 
      return "Nessun nome corrispondente."; 
     $nomi = array(); 
     $i = 0; 
     while($this->stmt->fetch()){ 
     $nomi[$i]["nome"] = $nome; 
      } 


     return $nomi; 

    } 

我怎麼可以在當前頁面上查看我的查詢結果表中的?我不想在另一個頁面中查看結果,而是在搜索表單所在的頁面中查看結果。

+1

對於您必須使用Ajax jQuery的使用呼叫PHP函數。你可以在當前頁面div中替換你的結果div,而不必刷新你的當前頁面。 –

回答

0
***HTML*** 

    <center><form method="post" id="search" action="search.php?go"> 

      <p> 

       <input type="text" name="name" id="name" /> 

       <input type="submit" id="search_btn" name="submit" value="Cerca utente" /> 
      </p> 

     </form></center> 

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> 

    <script> 
    $(document).ready(function(){ 

    $('#search_btn').click(function(){ 

    var Name=$('#name').val(); 
    $.Post('Search.php',{Name:Name},function(data) 
{ 
alert(data); 
}); 

    }); 


    }); 
    </script> 

PHP(必須保存爲search.php中)

<?php 
if($_isset($_POST["Name"])) 
{ 
$Name=$_POST["Name"]; 


searchUser($Name); 

public function searchUser($nomeUtente) 
    { 

     $sql = "SELECT uUsername FROM users WHERE='$nomeUtente' "; 

     if(!$this->stmt = $this->mysqli->prepare($sql)) 
      throw new Exception("MySQL Prepare statement failed: ".$this->mysqli->error); 

     $this->stmt->execute(); 
     $this->stmt->store_result(); 
     $this->stmt->bind_result($nome); 
     if($this->stmt->num_rows == 0) 
      return "Nessun nome corrispondente."; 
     $nomi = array(); 
     $i = 0; 
     while($this->stmt->fetch()){ 
     $nomi[$i]["nome"] = $nome; 
      } 


     return $nomi; 

    } 

} 

?>