note 114547 deleted from mysqli-stmt.bind-param by cmb
| From: | cmb@php.net | Date: | Sun, 22 Sep 2019 08:05:33 +0000 |
| Subject: | note 114547 deleted from mysqli-stmt.bind-param by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212313@lists.php.net to get a copy of this message | ||
Note Submitter: markac
----
Sprintf parameter binding style:
<?php
class MySqliDecorator {
private $db;
private $map = array(
'%d' => 'i', //integer
'%f' => 'd', //float
'%s' => 's', //string
);
public function __construct(mysqli $db) {
$this->db = $db;
}
public function prepare($query, &$params = array()) {
$expr = '/(' . implode('|', array_keys($this->map)) . ')/';
if (preg_match_all($expr, $query, $matches)) {
$types = implode('', $matches[0]);
$types = strtr($types, $this->map);
$query = preg_replace($expr, '?', $query);
if ($stmt = $this->db->prepare($query)) {
array_unshift($params, $types);
if (call_user_func_array(array($stmt, 'bind_param'), &$params)) {
return $stmt;
} else {
return false;
}
} else {
return false;
}
} else {
return $this->db->prepare($query);
}
}
}
?>
Using:
<?php
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$stmt = new MySqliDecorator($db);
$params = array(1, 'johny');
$stmt = $stmt->prepare('SELECT * FROM users WHERE Id = %d OR Username = %s',
$params);
$stmt->execute();
?>
Be careful when using % with LIKE and so on.