2016-01-08 28 views
3

我PDO類有一個叫做bindParams功能,其中有2個參數:setValues方法和的setType,自動分配一個PDO型

輸出的結果應該是這樣的:

$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是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) 

如果我沒有弄錯,我應該只執行沒有任何回聲的代碼來運行它。

謝謝您的幫助

回答

4

正在發生的事情是,當你通過循環設置$的setType第一次,在後續的迭代,is_null($的setType)返回false,所以switch語句從不計算。

根據你是否打算傳入$ setType,你可以做幾件不同的事情。如果你不這樣做,那麼你應該刪除$ setType參數和is_null檢查,然後在switch語句之後將你的調用添加到bindParam($ getVal,$ setType)。另外,要小心你的switch語句值:你可能想要切換(true)(或者只是使用if語句)而不是switch($ getVal),因爲根據實際值你也會得到不同的結果(不只是輸入)$ getVal。

+1

使用'gettype'會更好地識別類型並防止任何類型的歧義 - http://php.net/gettype – Clay

+0

是的,我正在尋找4個params:NULL,INT,STR或BOOL,..我從來沒有在我的bindParams中使用其餘的 – Fred