2014-02-25 46 views
-2

我只是想知道如果有人知道任何好的方法來防止Sql注入此代碼。我想要的最後一件事是有人盜用我的數據庫。我對此很新,希望聽到專家的意見。謝謝。防止此代碼上的SQL注入方法

<?php 
    $input = $_GET['input'];//Note to self $input in the name of the search feild 
    $terms = explode(" ", $input); 
    $query = "SELECT * FROM content WHERE "; 

    foreach ($terms as $each){ 
     $i++; 
     if ($i == 1) 
      $query .= "keywords LIKE '%$each%' "; 
     else 
      $query .= "OR keywords LIKE '%$each%' "; 
    } 

    // connecting to our mysql database 
    mysql_connect("localhost", "username", "password"); 
    mysql_select_db("database"); 

    $query = mysql_query($query); 
    $numrows = mysql_num_rows($query); 

      if ($numrows > 0){ 
       $i = 0; 
          while ($row = mysql_fetch_assoc($query)){ 
           $i++; 

      $id = $row['id']; 
      $title = $row['title']; 
      $description = $row['description']; 
      $keywords = $row['keywords']; 
      $link = $row['link']; 
      $plink = $row ['plink']; 
      $views = $row ['views']; 

       if($i == 3){ 
      echo '<td valign="top" "width="248" height="100%"> 
      <table width="100%" border="0"> 
      <tr> 
       <td align="center" valign="top"><a href='.$link.'> 
       <img src='.$plink.'width="200" height="151" vspace="5" /> 
      <br><b><a href='.$link.'>'.$title.'</b></a> 
       <br><strong><span style="line-height:20px">Total views: '.$views.'</span></strong> 
       </td> 
        </tr> 
       </table> 
       </td><tr>'; 



      } 


      else{ 

      echo '<td valign="top" "width="248" height="100%"> 
      <table width="100%" border="0"> 
      <tr> 
       <td align="center" valign="top"><a href='.$link.'> 
       <img src='.$plink.'width="200" height="151" vspace="5" /> 
      <br><b><a href='.$link.'>'.$title.'</b></a> 
       <br><strong><span style="line-height:20px">Total views: '.$views.'</span></strong> 
       </td> 
        </tr> 
       </table>' 
          ; 

       } 
        } 


     } 





    else 
     echo "No results found for \"<b>$input</b>\""; 



    // disconnect 
    mysql_close(); 
?> 
+3

[**在新的代碼,請不要使用'mysql_ *'功能**](http://bit.ly/phpmsql)。他們不再被維護[並且被正式棄用](http://j.mp/XqV7Lp)。看到[**紅框**](http://j.mp/Te9zIL)?學習[*準備的語句*](http://j.mp/T9hLWi),並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [這篇文章](http://j.mp/QEx8IB)將幫助你決定哪個。如果你選擇PDO,[這裏是一個很好的教程](http://j.mp/PoWehJ)。 –

+0

在這裏檢查http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – krishna

+0

與[parametrerized]一起使用PDO(http://stackoverflow.com/問題/ 60174/how-can-i-prevent-sql -injection-in-php?rq = 1)查詢。 – Rikesh

回答

0
  1. 首先DONOT使用mysql_ *喜歡的mysql_query,的mysql_connect等

  2. 使用的mysqli或PDO的功能,當你從用戶獲取數據,以便隨時使用由@指出預處理語句我可以有Cheezburger。

文檔鏈接:http://php.net/manual/en/book.pdo.php

如果仍然使用的是mysql_ *函數,然後使用mysql_real_escape_string和ヶ輛。

但建議使用Prepared語句切換到mysqli或PDO。

教程:http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059