我正在PDOStatement
上构建一个扩展程序,以named
或?
参数的形式自动绑定值mysqli
函数的 // Named params, converted to int and str.
$db->prepare('SELECT * FROM table WHERE id = :a AND somecol = :b')->run('is', [':a' => 69, ':b' => 'somestring']);
// Index params, converted to double and lob (else statement, ignore this)
$db->prepare('SELECT * FROM table WHERE coord = ? AND img = ?')->run('dl', $coord, $img);
样式}。我希望它有点像这样:
PDOStatement
我已将以下函数添加到扩展 public function run(string $types, ...$args){
foreach($args as $var){
if(is_array($var)){
// this is the code for the :named params.
if(count($types = str_split($types)) == count($var)){
// the types string matches the length of the given arguements.
$i = 0;
array_walk($var, function($val,$key) use ($types, $i){
echo $key, '=>', $val, '->', $types[++$i], '<br>';
});
} else {
// error, length of types does not match the length of the array.
}
} else {
// This is the code for ? params.
}
}
}
的类:
:a=>69->i
输出::b=>somestring->i
和$i
。显然$types = str_split($types)
没有增加,但问题是两个数组都不同,我使用 $types = [
0 => 'i',
1 => 's'
];
$var = [
':a' => 69,
':b' => 'somestring',
];
到下面的数组:
$var
解决方案是使用foreach循环$types[$i]
并在循环内增加$ i以引用$i
,这样我就可以设置一个参数。
问题在于我希望尽可能高效地执行此操作,这意味着我希望在1次迭代中执行此操作,最好不要使用array_shift()
变量。
我正在运行关于如何循环两个数组的空白,因为可能存在我忘记的函数。
我找到了一个解决方案,睡个好觉可以做什么:
我的解决方案是使用$types
来获取并删除private function getParam($type){
switch($type){
case 's':
case 'f':
case 'd': return PDO::PARAM_STR;
case 'i': return PDO::PARAM_INT;
case 'b': return PDO::PARAM_BOOL;
case 'n': return PDO::PARAM_NULL;
case 'l':
case 'r': return PDO::PARAM_LOB;
default:
// should log this issue.
return PDO::PARAM_STR;
}
}
public function run(string $types, ...$args){
$t = str_split($types);
$i = 1;
foreach($args as $var){
if(is_array($var)){
if(count($t) == count($var)){
foreach($var as $key => $val){
$this->bindValue($key, $val, $this->getParam(array_shift($t)));
}
} else {
throw new StatementError('1 type should be set for each arguement');
}
} else {
// No error checks, perhaps let PDO take care of it entirely instead
$this->bindValue($i++, $var, $this->getParam(array_shift($t)));
}
}
$this->result = $this->execute();
return $this;
}
private function __construct($dbh){
$this->dbh = $dbh;
}
中返回其值的第一个数字键。
scrollTo