2017-07-25 34 views
0

有沒有在PDOStatement::execute中指定PDO::PARAM_INT的方法?PDO :: PARAM_INT在PDOStatement ::執行

我習慣做如下結果:

$STH = $DBH->prepare('INSERT INTO items (name, description) VALUES (:name, :description)'); 
$STH->execute(array(':name' => $name, ':description' => $description)); 

但是,已經被插入的值必須是整數的時候..

據我所知,人們可以使用bindValuebindParam ..

$STH->bindParam(':price', $price, PDO::PARAM_INT); 

不過,我想是這樣的:

$STH->execute(array(':price' => array('value' => $price, 'type' => PDO::PARAM_INT))); 

這是否存在?

+0

['PDOStatement :: execute()'](http://php.net/manual/en/pdostatement.execute.php)只需要一個參數 - 一個$ input_parameters數組,因此您需要使用'bind *'函數明確。 –

+0

爲什麼不在驗證過程中確保它是一個整數? – brianforan

+0

手冊中有一些示例僅針對您所問的問題,您有沒有看過/嘗試過? –

回答

1

取自以下範例的例子,儘管您在這裏要做的是什麼。

注意:我發佈這個作爲社區維基答案,因爲我把他們從現有的代碼。

this user contributed notebindValue()

/* 
    method for pdo class connection, you can add your cases by yourself and use it. 
*/ 
class Conn{ 
.... 
.... 
private $stmt; 
public function bind($parameter, $value, $var_type = null){ 
     if (is_null($var_type)) { 
      switch (true) { 
           case is_bool($value): 
        $var_type = PDO::PARAM_BOOL; 
        break; 
       case is_int($value): 
        $var_type = PDO::PARAM_INT; 
        break; 
       case is_null($value): 
        $var_type = PDO::PARAM_NULL; 
        break; 
       default: 
        $var_type = PDO::PARAM_STR; 
      } 
     } 
     $this->stmt->bindValue($parameter, $value, $var_type); 
    } 

this user contributed notebindParam()

<?php 
/** 
* @param string $req : the query on which link the values 
* @param array $array : associative array containing the values ??to bind 
* @param array $typeArray : associative array with the desired value for its corresponding key in $array 
* */ 
function bindArrayValue($req, $array, $typeArray = false) 
{ 
    if(is_object($req) && ($req instanceof PDOStatement)) 
    { 
     foreach($array as $key => $value) 
     { 
      if($typeArray) 
       $req->bindValue(":$key",$value,$typeArray[$key]); 
      else 
      { 
       if(is_int($value)) 
        $param = PDO::PARAM_INT; 
       elseif(is_bool($value)) 
        $param = PDO::PARAM_BOOL; 
       elseif(is_null($value)) 
        $param = PDO::PARAM_NULL; 
       elseif(is_string($value)) 
        $param = PDO::PARAM_STR; 
       else 
        $param = FALSE; 

       if($param) 
        $req->bindValue(":$key",$value,$param); 
      } 
     } 
    } 
} 

/** 
* ## EXEMPLE ## 
* $array = array('language' => 'php','lines' => 254, 'publish' => true); 
* $typeArray = array('language' => PDO::PARAM_STR,'lines' => PDO::PARAM_INT,'publish' => PDO::PARAM_BOOL); 
* $req = 'SELECT * FROM code WHERE language = :language AND lines = :lines AND publish = :publish'; 
* You can bind $array like that : 
* bindArrayValue($array,$req,$typeArray); 
* The function is more useful when you use limit clause because they need an integer. 
* */ 
?>