note 114547 added to mysqli-stmt.bind-param
| From: | markac | Date: | Wed, 05 Mar 2014 15:09:46 +0000 |
| Subject: | note 114547 added to mysqli-stmt.bind-param | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-198798@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 46.17.113.2
Probable Submitter: 91.192.89.35
----
Manual Page -- http://php.net/manual/en/mysqli-stmt.bind-param.php
Edit -- https://master.php.net/note/edit/114547
Del: integrated -- https://master.php.net/note/delete/114547/integrated
Del: useless -- https://master.php.net/note/delete/114547/useless
Del: bad code -- https://master.php.net/note/delete/114547/bad+code
Del: spam -- https://master.php.net/note/delete/114547/spam
Del: non-english -- https://master.php.net/note/delete/114547/non-english
Del: in docs -- https://master.php.net/note/delete/114547/in+docs
Del: other reasons-- https://master.php.net/note/delete/114547
Reject -- https://master.php.net/note/reject/114547
Search -- https://master.php.net/manage/user-notes.php