2015-01-07 51 views
-1

我創建了功能在PHP中保存選擇更新和刪除。轉換sql添加更新和刪除功能到mysqli

plz告訴我如何使這個函數更強大,以防止mysql注入。

Bcoz我在不同的文件中多次調用這個函數。

Plz建議。

下面是我的功能和類。

class DB 
{ 
    var $host = 'localhost'; 
    var $user = 'root'; 
    var $password = ''; 
    var $database = 'bhaskar_hindi_dbs';  

    function __construct($host = '', $user = '', $password = '', $database = '') 
    { 
     if($host != '') $this->host = $host; 
     if($user != '') $this->user = $user; 
     if($password != '') $this->password = $password; 
     if($database != '') $this->database = $database; 
     $con = mysql_connect($this->host, $this->user,$this->password) OR die('Couldnot connect to mysql Server'); 
     mysql_select_db($this->database) OR die('Couldnot connect to mysql database '.$this->database); 
    } 


    function save($table, $fields, $condition = '') 
    { 
     mysql_set_charset('utf8'); 
     $sql = "INSERT INTO $table SET "; 
     if($condition != '') 
      $sql = "UPDATE $table SET "; 
     $table_fields = $this->get_table_fields($table); 
     foreach($fields as $field=>$value) 
     { 
      if(in_array($field,$table_fields)) 
      $sql .= "$field = '".mysql_real_escape_string(trim(htmlspecialchars($value)))."', ";    
     } 
     $sql = substr($sql, 0 ,-2); 
     if($condition !='') 
     $sql .="modified = NOW()"; 
     else 
     $sql .="created = NOW(), modified = NOW()"; 
     if($condition != '') 
      $sql .= " WHERE $condition"; 
       $result = mysql_query($sql); 
     if(mysql_affected_rows()) 
      return true; 
     else 
      return false; 
    } 

function select($table, $fields = array(), $condition = '',$order = '') 
    { 
     $data = array(); 
     mysql_set_charset('utf8'); 
     $sql = "SELECT "; 
     if(is_array($fields) && count($fields) > 0) 
     { 
      $sql .= implode(", ",$fields); 
     } 
     else 
     { 
      $sql .= "*"; 
     } 
     $sql .= " FROM $table"; 
     if($condition != '') 
      $sql .= " WHERE $condition"; 
     if($order != '') 
      $sql .= " ORDER BY $order";  
     $result = mysql_query($sql);   
     while($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
     { 
      $data[] = $row; 
     }  
     return $data; 
    } 

function get_table_fields($table) 
    { 
     $fields = array(); 
     $result = mysql_query("SHOW COLUMNS FROM $table"); 
     while($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
     { 
      $fields[] = $row['Field']; 
     } 

     return $fields; 
    } 

} 

下面是我的代碼來調用的功能,如聰明...

<?php 
require_once('includes/config.php'); 
$Admin = new admins; 
$cond = "send_top = 'Active'"; 
$ord = "top_priority ASC"; 
$top2 = $Admin->select($Admin->news_table,'',$cond,$ord); 
?> 

回答

0

轉換到庫MySQLi不會阻止XSS攻擊,請發表攻擊的詳細 描述。

+0

但mysqli是先進的版本,然後mysql和不需要轉義數據和許多新的增強...這就是爲什麼我需要跳轉到mysqli。 –

+0

XSS和SQL注入是兩個不同的問題,使用mysql或mysqli函數轉義值只會阻止後面的兩個問題,這就是爲什麼我要求你描述你的問題。 –

+0

我需要使安全我的代碼從sql injection.so plz建議如何使從mysql注入這個功能更強。 –