2016-01-22 49 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

相关问题