2014-09-27 43 views
-2

我有一個PHP網站來顯示產品。我需要介紹一個'搜索'功能,可以在多個產品中找到關鍵字或短語。搜索PHP網站與MySQL數據庫的腳本

我經歷了一些現有的腳本,並寫了/修改了一個雖然能夠連接到數據庫,但不返回任何值。調試模式會發出警告「mysqli_num_rows()期望參數1爲mysqli_result,布爾給定」。似乎我沒有正確收集查詢值。在PHP手冊說,mysqli_query()回報失敗和成功的SELECT,SHOW FALSE,描述或解釋查詢mysqli_query()會返回一個mysqli_result對象和其他成功的查詢mysqli_query()將返回TRUE」。

有什麼建議?

<form name="search" method="post" action="search.php"> 
     <input type="text" name="searchterm" /> 
     <input type="hidden" name="searching" value="yes" /> 
     <input type="submit" name="submit" value="Search" /> 
    </form> 

    <?php 
    $searchterm=trim($_POST['searchterm']); 
    $searching = $_POST['searching']; 
    $search = $_POST['search']; 

    //This is only displayed if they have submitted the form 
    if ($searching =="yes") 
    { 
     echo 'Results'; 

     //If they forget to enter a search term display an error 
     if (!$searchterm) 
     { 
      echo 'You forgot to enter a search term'; 
      exit; 
     } 

     //Filter the user input 
     if (!get_magic_quotes_gpc()) 
      $searchterm = addslashes($searchterm); 

     // Now connect to Database 
     @ $db = mysqli_connect('localhost','username','password','database'); 

     if (mysqli_connect_errno()) { 
      echo 'Error: Could not connect to the database. Please try again later.'; 
      exit; 
     } 
     else { 
      echo "Database connection successful."; //Check to see whether we have connected to database at all! 
     } 
     //Query the database 
     $query = "SELECT * FROM wp_posts WHERE post_title LIKE '%$searchterm%' OR post_excerpt LIKE '%$searchterm%' OR post_content LIKE '%$searchterm%'"; 
     $result = mysqli_query($db, $query); 

     if (!$result) 
      echo "No result found"; 

     $num_results = mysqli_num_rows($result); 

     echo "<p>Number of match found: ".$num_results."</p>"; 

     foreach ($result as $searchResult) { 
      print_r($searchResult); 
     } 

     echo "You searched for $searchterm"; 

     $result->free(); 
     $db->close(); 
    } 
+0

更正了@Rasclatt指出的錯誤代碼。 – Manish 2014-09-27 11:35:30

+0

那你有工作嗎? – Rasclatt 2014-09-27 16:03:15

+0

不,它沒有。如上所述,似乎我無法在'mysqli_query()'函數中正確收集返回對象/值。 – Manish 2014-09-27 16:53:55

回答

0

我想應該是在查詢像'%$searchterm%',不'%{searchterm}%'。你是不是在尋找你的榜樣您的變量$searchterm

谷歌的顯示使用LIMIT,因此它一次只顯示一定數量的結果(稱爲pagination)。

這是測試和工作。你將需要在搜索引擎類中更改1)db連接信息。 2)如果你想要它在不同的頁面上,你將不得不分裂它。如果沒有,將這整個代碼複製到一個頁面,它將在該頁面上工作。

<?php 
    class DBEngine 
     { 
      protected $con; 
      // Create a default database element 
      public function __construct($host = '',$db = '',$user = '',$pass = '') 
       { 
        try { 
          $this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING)); 
         } 
        catch (Exception $e) { 
          return 0; 
         } 
       } 

      // Simple fetch and return method 
      public function Fetch($_sql) 
       { 
        $query = $this->con->prepare($_sql); 
        $query->execute(); 

        if($query->rowCount() > 0) { 
          $rows = $query->fetchAll(); 
         } 

        return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0; 
       } 

      // Simple write to db method 
      public function Write($_sql) 
       { 
        $query = $this->con->prepare($_sql); 
        $query->execute(); 
       } 
     } 

    class SearchEngine 
     { 
      protected $searchterm; 
      public function execute($searchword) 
       { 
        $this->searchterm = htmlentities(trim($searchword), ENT_QUOTES); 
       } 

      public function display() 
       { ?> 
        <h1>Results</h1> 
       <?php 

        //If they forget to enter a search term display an error 
        if(empty($this->searchterm)) { ?> 
        <h3>Search Empty</h3> 
        <p>You must fill out search field.</p> 
        <?php } 
        else { 
          $con  = new DBEngine('localhost','database','username','password'); 
          $results = $con->Fetch("SELECT * FROM wp_posts WHERE post_title LIKE '%".$this->searchterm."%' OR post_excerpt LIKE '%".$this->searchterm."%' OR post_content LIKE '%".$this->searchterm."%'"); 

          if($results !== 0 && !empty($results)) { ?> 
            <p>Number of match found: <?php echo count($results); ?> on search:<br /> 
            <?php echo strip_tags(html_entity_decode($this->searchterm)); ?></p> 
            <?php 
            foreach($results as $rows) { 
              echo '<pre>'; 
              print_r($rows); 
              echo '</pre>'; 
             } 
           } 
          else { ?> 
            <h3>No results found.</h3> 
            <?php 
           } 
         } 
       } 
     } 

    if(isset($_POST['submit'])) { 
      $searcher = new SearchEngine(); 
      $searcher->execute($_POST['searchterm']); 
      $searcher->display(); 
     } ?> 
    <form name="search" method="post" action=""> 
     <input type="text" name="searchterm" /> 
     <input type="hidden" name="searching" value="yes" /> 
     <input type="submit" name="submit" value="Search" /> 
    </form> 
+0

@Rascallat良好的觀察。將其更改爲「%$ searchterm%」。但沒有幫助。查詢結構是否正確? – Manish 2014-09-27 07:48:28

+0

看起來正確。它只是說0行返回? – Rasclatt 2014-09-27 07:56:05

+0

不。對於找到的結果數量,它呈現空白。 – Manish 2014-09-27 08:08:21

0

做你的文字搜索,你擁有它,你將需要更改代碼'%{searchterm}%''%$searchterm%',因爲the brackets aren't needed和你搜索短語「{}搜索關鍵詞。」除此之外,您可能需要查看FULLTEXT search capabilities,因爲您正在使用當前方法進行文字搜索。

爲了使輸出看起來像Google的輸出,您只需爲每個搜索結果編寫一個包裝器,並使用CSS和HTML對其進行設計。