如何在SQL查询中使用变量

时间:2017-08-15 08:31:29

标签: php mysql

我写了一个类Database.php:

class Database
{
    private $host;
    private $dbUsername;
    private $dbPassword;
    private $connection;
    private $iv;
    public function __construct($host, $dbUsername, $dbPassword, $iv)
    {
        $this->dbPassword = $dbPassword;
        $this->dbUsername = $dbUsername;
        $this->host = $host;
        $this->iv = $iv;

    }

    public function createDatabase($dbName){
        $this->connection = mysqli_connect($this->host, $this->dbUsername, $this->dbPassword);
        $query = "CREATE DATABASE IF NOT EXISTS $dbName";
        if(!$this->connection){
            var_dump("Connection failed");
        }
        else {
            $this->connection->prepare($query)->execute();
        }
        $this->connection->close();
    }

    public function createTable($query, $dbName){
        $this->connection = mysqli_connect($this->host, $this->dbUsername, $this->dbPassword, $dbName);
        if(!$this->connection){
            var_dump("Connection failed");
        }
        else {
            $this->connection->prepare($query)->execute();
        }
        $this->connection->close();
    }

    public function getConnection(){
        $this->connection = mysqli_connect($this->host, $this->dbUsername, $this->dbPassword);
        return $this->connection;
    }

    public function executeQuery($dbname, $query){
        $this->connection = mysqli_connect($this->host, $this->dbUsername, $this->dbPassword, $dbname);
        if(!$this->connection){
            var_dump("Connection failed");
            return false;
        }
        else{
            $this->connection->prepare($query)->execute();
            $this->connection->close();
            return true;
        }

    }

    public function deleteFromTable($dbname, $query){
        $this->connection = mysqli_connect($this->host, $this->dbUsername, $this->dbPassword, $dbname);
        if(!$this->connection){
            var_dump("Connection failed");
            return false;
        }
        else{
            $this->connection->prepare($query)->execute();
            $this->connection->close();
            return true;
        }
    }

    public function check($query){
        $this->connection = mysqli_connect($this->host, $this->dbUsername, $this->dbPassword, "portal");;
        $statement = $this->connection->prepare($query);
        $statement->execute();
        $statement->store_result();
        if($statement->num_rows != 0){
            $this->connection->close();
            return true;
        }

        else
        {
            $this->connection->close();
            return false;
        }
    }

    public function getId($username){
        $this->connection = mysqli_connect($this->host, $this->dbUsername, $this->dbPassword, 'portal');
        $id = mysqli_fetch_all(mysqli_query($this->connection, "SELECT id FROM users WHERE username='$username'"));
        $this->connection->close();
        return $id[0][0];
    }

    public function getData($query, $name = null){
        $this->connection = mysqli_connect($this->host, $this->dbUsername, $this->dbPassword, 'portal');
        $statement = $this->connection->prepare($query);
        $statement->execute();
        $data = $statement->get_result()->fetch_array();
        if($name != null) {
            return $data[$name];
        }
        else{
            return $data;
        }
    }

    public function getDataAsArray($myQuery){
        $this->connection = mysqli_connect($this->host, $this->dbUsername, $this->dbPassword, 'portal');
        $query = mysqli_query($this->connection, $myQuery);
        $results = array();
        while($line = mysqli_fetch_array($query)){
            $results[] = $line;
        }
        return $results;
    }

    public function encryptSSL($data){
        $encryptionMethod = "AES-256-CBC";
        $secretHash = "";
        $encryptedMessage = openssl_encrypt($data, $encryptionMethod, $secretHash, 0, $this->iv);
        return $encryptedMessage . '||' . $this->iv;
    }
    public function decryptSSL($data, $iv){
        $encryptionMethod = "AES-256-CBC";
        $secretHash = "";
        $decryptedMessage = openssl_decrypt($data, $encryptionMethod, $secretHash, 0,  $iv);
        return $decryptedMessage;
    }

}

我在我的代码中使用它作为以下选项,更新,删除数据库中的条目:

$customerInfo = $database->getData("SELECT * FROM customers WHERE id='$id'");

$database->executeQuery('portal', "INSERT into messages (userId, message, customerId, messageRead, messageTrash, messageDeleted, time_added, subject) VALUES(
                                                            '$id', '$message', '$customerId', 0, 0, 0, '$time_date', '$messageSubject')");

但是很多人都知道这对于SQL注入是不安全的。像:ID这样的绑定参数是可能的,但我不知道如何在课堂上做到这一点。如果我想要一个函数但是有多个不同的查询,例如:一个查询带有一个变量,或者一个查询有多个变量,如上面两个查询,该怎么办

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

在没有首先转义/处理它们的情况下直接在查询中使用变量绝不是一个好主意。但是,如果你这样做,使用php的'bif'mysqli_real_escape_string($ var)来逃避它们。

在您的代码中,您可以执行以下操作:

$customerInfo = $database->getData(sprintf("SELECT * FROM customers WHERE id='%d'", mysqli_real_escape_string($id)));

$database->executeQuery('portal', sprintf("INSERT into messages (userId, message, customerId, messageRead, messageTrash, messageDeleted, time_added, subject) VALUES('%d', '%s', '%s', 0, 0, 0, '%s', '%s')", mysqli_real_escape_string($id), mysqli_real_escape_string($message), mysqli_real_escape_string($customerId), mysqli_real_escape_string($time_date), mysqli_real_escape_string($messageSubject)));

以下是使用strtr执行此操作的另一种方法:

$placeholders = array(
  ':id' => mysqli_real_escape_string($id),
  ':message' => mysqli_real_escape_string($message),
  ':customerId' => mysqli_real_escape_string($customerId),
  ':time_date' => mysqli_real_escape_string($time_date),
  ':messageSubject' => mysqli_real_escape_string($messageSubject),
);

$database->executeQuery('portal', strtr("INSERT into messages (userId, message, customerId, messageRead, messageTrash, messageDeleted, time_added, subject) VALUES(':id', ':message', ':customerId', 0, 0, 0, ':time_date', ':messageSubject')", $placeholders));