db类:我怎样才能避免sql注入?

时间:2015-03-12 10:05:42

标签: php mysql oop

我是PHP新手,并开始使用DB类。我想知道如何避免SQL注入。在程序PHP中,我总是使用$ db-> real_escape_string,这在这里不起作用。

DB.class.php

class DB {    
    protected $db_name = '';
    protected $db_user = '';
    protected $db_pass = '';
    protected $db_host = '';
    protected $connection;

    public function connect() {
        $this->connection = mysqli_connect($this->db_host, $this->db_user, $this->db_pass);
        mysqli_select_db($this->connection, $this->db_name);

        return true;
    }

    public function processRowSet($rowSet, $singleRow = false) {
        $resultArray = array();
        while ($row = mysqli_fetch_assoc($rowSet)) {
            array_push($resultArray, $row);
        }

        if ($singleRow === true)
            return $resultArray[0];

        return $resultArray;
    }

    public function insert($data, $table) {
        $columns = "";
        $values = "";

        foreach ($data as $column => $value) {
            $columns .= ($columns == "") ? "" : ", ";
            $columns .= $column;
            $values .= ($values == "") ? "" : ", ";
            $values .= $value;
        }

        $sql = "insert into $table ($columns) values ($values)";

        mysqli_query($this->connection, $sql) or die(mysqli_error($this->connection));

        //return the ID of the user in the database.
        return mysqli_insert_id($this->connection);
    }
}

使用的一个例子来自:

insert-entry.php

require_once 'db.php';

$headline = $_POST['headline'];
$description = $_POST['description'];

$data = array(
        'headline' => $headline,
        'description' => $description
    );

$db->insert($data, 'entries');´

为了确保避免SQL注入,我需要做哪些调整?

1 个答案:

答案 0 :(得分:2)

Doro,你需要使用预准备语句,这意味着你不要直接在SQL字符串中输入数据,而是看起来像:

库MySQLi

UPDATE table SET value1 = ? , value2 = ? WHERE value3 = ? LIMIT 1

PDO

 UPDATE table SET value1 = :val1 , value2 = :val2 WHERE value3 = :strVal3 LIMIT 1

然后按顺序传递值,在bind_param函数(带有MySQli的,语法与PDO 略有不同)中,在插入之前清除值的SQL注入风险。这些值将替换?占位符。 PDO使用样式:referencedString稍微不同的引用占位符,而不是MySQLi的简单?。您可以使用两种类型的Prepared语句,MySQLi和PDO,MySQLi更容易迁移到,PDO在语法上稍微更合乎逻辑(并且更短)。

研究MySQL Prepared Statements以及阅读Clive提供的链接。