2016-01-22 42 views
-3

我想做一個搜索引擎,但是當我上傳此代碼到我的網站,我得到爲什麼我的網站不能理解我的MySQL和PHP代碼?

錯誤003:發生未知的錯誤。

我去了phpmyadmin並在SQL選項卡中輸入了SQL,我得到了正確的結果,但是當我將它上傳到我的網站時,它不起作用。

<?PHP 

    global $output; 
    if(isset($_POST['submit'])){ 
      if(!empty($_POST)) { 
      //Connect to DB 
      $conn = new mysqli('localhost', 'username', 'password', 'search')or die('ERROR 001: Something went wrong while connecting to MySQL server.'); 

      if ($conn->connect_error) { 
       die("Connection failed: " . $conn->connect_error); 
      } 

      $search = $_POST['searchBar']; 

      $result = $conn->query('SELECT * FROM websites WHERE url LIKE "%$search%" OR title LIKE "%$search%"')or die('ERROR 002: Something is wrong with you SQL.'); 

      if(!$result->num_rows == 0) { 
       while($row = $result->fetch_assoc()) { 
        $title = $row['title']; 
        $url = $row['url']; 
        $id = $row['id']; 

        $output .= '<a href="' . $url . '" target="_blank">' . $title . '</a><br><br>'; 
       } 
      } else { 
       $output = 'ERROR 003: An unknown error occurred.'; 
      } 
     } 
    } 

?> 

<?PHP 

    require('search.php'); 

?> 

<!DOCTYPE HTML> 
<HTML lang = "en"> 
    <head> 
     <meta charset = "UTF-8"> 
     <meta name = "description" content = "null"> 
     <meta name = "author" content = "Adam Oates"> 
     <meta name = "title" content = "Search Engine"> 
     <title title = "Gigaboy Search Engine"> 
      Gigaboy Search Engine 
     </title> 
     <link rel = "apple-touch-icon" href = ""> 
     <link rel = "shortcut icon" href = ""> 
     <link rel = "stylesheet" type = "text/css" href = "main.css"> 
     <script type = "text/javascript" src = "http://code.jquery.com/jquery-2.1.4.js"></script> 
     <script type = "text/javascript" src = "main.js"></script> 
    </head> 
    <body> 
     <header> 

     </header> 

     <section id = "mainIndex"> 
      <div align = "center"> 
       <form action = "index.php" method = "post"> 
        <input type = "text" name = "searchBar" placeholder = "Search the Web" autocomplete = "off"> 
        <input type = "submit" name = "submit" value = "Search"> 
       </form><br><br> 
       <?PHP echo $output; ?> 
      </div> 
     </section> 

     <footer> 

     </footer> 
    </body> 
</HTML> 
+1

這意味着'$ result-> num_rows == 0'是'true'。這是正確的在你自己的代碼... – Mike

+0

我知道'$ result-> num_rows == 0'是'true'我需要它是'false'。 –

+0

如果將if邏輯更改爲if($ result-> num_rows> 0){...}',會發生什麼情況? –

回答

0

當執行MYSQL查詢使用模式前綴:

SELECT * FROM [SCHEMA].websites WHERE url LIKE '%".$search."%' OR title LIKE '%".$search%."'; 

,並把正確的搜索變量,我把查詢。

我推薦使用準備好的語句這樣你可以避免SQL注入

+1

爲什麼在括號中有'[SCHEMA]'?這是MySQL,而不是SQL-Server。 – Barmar

+0

括號用作應放置指示放置字符串的佔位符。 – datelligence

+1

你爲什麼認爲他需要指定模式名稱?他在調用'new mysqli()'時指定了數據庫名稱。 – Barmar

相關問題