防止此代码上的SQL注入方法

时间:2014-02-25 05:37:48

标签: php 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();
?>

1 个答案:

答案 0 :(得分:0)

  1. 首先不要使用像mysql_query,mysql_connect等mysql_ *函数

  2. 使用mysqli或PDO,当您从用户那里获取数据时,请始终使用@I Can Has Cheezburger指出的Prepared语句。

  3. docs链接:http://php.net/manual/en/book.pdo.php

    如果您仍在使用mysql_ *函数,请使用mysql_real_escape_string和htmlentities。

    但建议使用Prepared语句切换到mysqli或PDO。

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