gpt4 book ai didi

php - PDOStatement::execute 中的 PDO::PARAM_INT

转载 作者:行者123 更新时间:2023-11-29 06:56:39 26 4
gpt4 key购买 nike

有没有办法在PDOStatement::execute中指定PDO::PARAM_INT

我习惯做以下事情......

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

这个存在吗?

最佳答案

示例取自以下内容,它们完全符合您想要在此处执行的操作。

旁注:我将其作为社区 wiki 答案发布,因为我确实将它们从现有代码中拉出来。

来自this user contributed note对于bindValue():

/*
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 note对于bindParam():

<?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.
* */
?>

关于php - PDOStatement::execute 中的 PDO::PARAM_INT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45310876/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com