自动分配 PDO 类型

Automatically assign a PDO type

我的 PDO class 有一个名为 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) returns false,因此 switch 语句永远不会计算。

您可以做几件不同的事情,具体取决于您是否真的打算传入 $setType。如果不这样做,则应删除 $setType 参数和 is_null 检查,然后在 switch 语句后添加对 bindParam($getVal, $setType) 的调用。

此外,请注意您的 switch 语句值:您可能想要 switch(true)(或只使用 if 语句),而不是 switch($getVal),因为根据实际值,您也会得到不同的结果(不仅仅是类型)$getVal.