我的PDO类有一个名为bindParams的函数,它有两个参数:setValues和setType,
输出结果应该是:
$insertNews->bindParam(':news_title', $newsTitle, PDO::PARAM_STR);
因此,我希望自动将"PDO::PARAM_STR"分配给它们的值,在我的情况下,"news_title"是变量setValues,"PDO:PARAM_STR"是setType:
public final function bindParams($setValues=array(), $setType = null){
//print_r($setValues);
foreach ($setValues as $getVal) {
echo $getVal.'<br />';
if (is_null($setType)) {
switch ($getVal) {
case is_int($getVal):
echo $getVal.' is INT<br />';
$setType = PDO::PARAM_INT;
break;
case is_bool($getVal):
echo $getVal.' is BOOL<br />';
$setType = PDO::PARAM_BOOL;
break;
case is_null($getVal):
echo $getVal.' is NULL<br />';
$setType = PDO::PARAM_NULL;
break;
default:
echo $getVal.' is STR<br />';
$setType = PDO::PARAM_STR;
}
}
}
} // end bindParams()
$con = new crud($dbCon);
$con->insert('ban_ip', array('visitor_type', 'ip'));
$con->bindParams(array('Visitor_Type', 1));
输出结果为:
访问者类型为STR
它没有循环另一个值,即1。
编辑:正确代码:
我认为这个有效:
public final function bindParams($setValues=array(), $setType = null){
$combine = array_combine($this->insertedKeys, $setValues);
foreach ($combine as $getKey => $getVal) {
//echo 'key '.$getKey.' val '.$getVal.'<br />';
switch ($getVal) {
case is_int($getVal):
echo $getVal .' is INT<br />';
$setType = 'PDO::PARAM_INT';
break;
case is_bool($getVal):
$setType = 'PDO::PARAM_BOOL';
echo $getVal .' is BOOL<br />';
break;
case is_null($getVal):
echo $getVal .' is NULL<br />';
$setType = 'PDO::PARAM_NULL';
break;
default:
echo $getVal .' is STR<br />';
$setType = 'PDO::PARAM_STR';
break;
}
echo "this->stmt->bindParams($getKey, $getVal, $setType)<br />";
}
} // end bindParams()
结果是:
Visitor_Type is STR
this->stmt->bindParams(visitor_type, Visitor_Type, PDO::PARAM_STR)
1 is INT
this->stmt->bindParams(ip, 1, PDO::PARAM_INT)
如果我没有错的话,我应该只执行没有任何回声的代码来运行它
感谢您的帮助
实际情况是,在循环中第一次设置$setType后,在随后的迭代中,is_null($setType)返回false,因此switch语句永远不会求值。
根据您是否真的打算传入$setType,您可以做一些不同的事情。如果没有,那么应该删除$setType参数和is_null检查,然后在switch语句之后添加对bindParam($getVal,$setType)的调用。
此外,要小心您的switch语句值:您可能想要switch(true)(或只使用if语句),而不是switch($getVal),因为根据$getVal的实际值(而不仅仅是类型),您也会得到不同的结果。