我的 PDO 类有一个名为 bindParams 的函数,它有 2 个参数: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));
输出结果为:
Visitor_Type is 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。
关于php - 自动分配 PDO 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34668956/