Очередной костыль экранирования mysqli запросов (Рейтинг: +3)

Печать RSS
Доброе утро!

костыль
<?php
class MysqliEsc {
    protected $link = null;
    public function __construct($host, $user, $password, $database, $port = 3306, $socket = null) {
        $this->link = new \mysqli($host, $user, $password, $database, $port, $socket);
    }
    /**
     * 
     * @param string $sql sql запрос вида select * from таблица where поле = (%s, %i...)
     * @param array $params Массив!!! с параметрами (параметром)
     * @return \mysqli_result 
     */
    public function query($sql, array $params = []) {
        if ($params) {
            $sql = vsprintf($sql, array_filter($params, function ($param){
                return $this->link->real_escape_string($param);
            }));
        }
        return $this->link->query($sql);
    }
}
Использование
<?php
$db = new MysqliEsc('localhost', 'root', '', 'silex');
var_dump($db->query('select * from users where id = %i', [1])->fetch_array());
вернет

array (size=22)
0 => string '1' (length=1)
'id' => string '1' (length=1)
1 => string '[email protected]' (length=18)
'email' => string '[email protected]' (length=18)
2 => string 'HQZgK/c3tX6LXvqaPZowmQ+uyKtr4HjjMs9QMe6ZNYx6GHTa+hOV06N/tm7DSWqRFJLhiC+WySIVoZmnrzqGzg==' (length=88)
'password' => string 'HQZgK/c3tX6LXvqaPZowmQ+uyKtr4HjjMs9QMe6ZNYx6GHTa+hOV06N/tm7DSWqRFJLhiC+WySIVoZmnrzqGzg==' (length=88)
3 => string 'lapn8gh0q1ccww0so4g8k4oog80soc0' (length=31)
'salt' => string 'lapn8gh0q1ccww0so4g8k4oog80soc0' (length=31)
4 => string 'ROLE_USER' (length=9)
'roles' => string 'ROLE_USER' (length=9)
5 => string 'mmmmmmmmmmm' (length=11)
'name' => string 'mmmmmmmmmmm' (length=11)
6 => string '1419016035' (length=10)
'time_created' => string '1419016035' (length=10)
7 => null
'username' => null
8 => string '1' (length=1)
'isEnabled' => string '1' (length=1)
9 => null
'confirmationToken' => null
10 => null
'timePasswordResetRequested' => null

UPD Предложение от Башка:

<?php 
class MyMysqli extends mysqli{ 
  public function myQuery($query, $params){ 
    $stmt = $this->prepare($query); 
    $p = array_values($params); 
    array_unshift($p, array_keys($params)); 
    call_user_func_array([$stmt, 'bind_param'], $p); 
    $result = $stmt->execute(); 
    $stmt->close(); 
    return $result; 
  } 
}                                                              
$mysql = new MyMysqli("localhost", "my_user", "my_password", "world"); 
$mysql->myQuery('SELECT * FROM users WHERE login = ?', ['s' => 'admin']);
Добавил:
Рейтинг: +3
Просмотры: 2416
Комментарии (14) »