如何在此类中阻止sql注入?

时间:2014-04-07 18:56:07

标签: php mysql sql mysqli

我正在尝试创建一个数据库类,并希望在其中包含real_escape字符串,但每当我这样做时,我都没有得到任何结果。请帮忙:

<!DOCTYPE html>
<head>
<title>PHP Classes</title>
</head>

<body>
<?php
class Database
{
    function Database($host, $user, $pass, $db){
        $this -> con = mysqli_connect($host, $user, $pass, $db);
    }
    function runQuery($query){
        mysqli_query($this -> con, $query);
    }
}
?>


<?php
    $database = new Database("localhost", "root", "", "website");
    $database -> runQuery("DELETE FROM subject WHERE name = 'Footer'");
?>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

根据您发布的代码,您不能这样做。您的班级接受已经汇编的查询,此时执行任何形式的清理或逃避都为时已晚。

您需要通过转发用户输入的数据来保护SQL注入,之前将它组装到查询中;理想情况下,您将通过参数化查询执行最终装配。

答案 1 :(得分:0)

我建议你在这个班级使用单身人士模式。

class Database
{
   private $database;   
   static $instance;

   private $query;
   private $result;


   private function __construct($params)
   {
       if($params!=null)
       {
           @$this->database = mysqli_connect($params->dbSettings['dbHostName'],$params->dbSettings['dbUserName'],$params->dbSettings['dbPassword']) or die('DB Error occured.');
           $this->query="";
           $this->result=null;
           mysqli_select_db($this->database,$class->dbSettings['dbName']);
       }    
       else
       {
           die('DB credentials not entered...');
            exit;   
       }
   }


   public static function GetInstance($params)
   {
       if(!(self::$instance instanceof self))
       {
          self::$instance = new self($params);  
       }            
       return self::$instance;
   }

   public function __destruct()
   {
       if($this->database)
       {
           mysqli_close($this->database);   
       }
   }

   public function ExecuteQuery($query)
   {                
        $this->query=addslashes($query);
        $this->result = mysqli_query($this->database,$query);
   }
   public function GetResult()
   {            
          if($this->result!=null)
          {
                 $returnArray=array();
                 $rows = mysqli_num_rows($this->result);
                 if($rows>0)
                 {                  
                        while($row = mysqli_fetch_assoc($this->result))
                        {
                               $returnArray[]=$row; 
                        }
                 }
                 return $returnArray;
          }
          else
          {
                 return null;
      }                      
   }            
}

注意!!!您必须过滤用户的所有数据。用于每个字段总是addslashes方法。此外,mysqli对sql注入有一些保护。