db class:如何避免 sql 注入?

db class: how can I avoid sql injection?

我是 PHP 的 OOP 新手,开始使用数据库 class。我想知道如何避免 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);
    }
}

这里有一个用法示例:

插入-entry.php

require_once 'db.php';

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

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

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

为了确保避免 SQL 注入,我需要在何处进行哪些调整?

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

我的SQL我

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,而 PDO 的语法稍微更合乎逻辑(并且简短)。

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