在网上搜索后,通过扩展PDOStatement 类最终得到以下解决方案。请记住,此学分来自 SE 和网络中的其他来源。
class CustomPDOStatement extends PDOStatement
{
public $removeNulls = FALSE;
public $dbh;
protected function __construct($dbh)
{
$this->dbh = $dbh;
}
public function execute($input_parameters = null)
{
if ($this->removeNulls === TRUE && is_array($input_parameters)) {
foreach ($input_parameters as $key => $value) {
if (is_null($value)) {
$input_parameters[$key] = '';
}
}
}
return parent::execute($input_parameters);
}
public function bindValue($parameter, $value, $data_type = PDO::PARAM_STR)
{
if ($this->removeNulls === TRUE && is_null($value)) {
$value = '';
}
return parent::bindValue($parameter, $value, $data_type);
}
public function bindParam($parameter, &$variable, $data_type = PDO::PARAM_STR, $length = null, $driver_options = null)
{
if ($this->removeNulls === TRUE && is_null($variable)) {
$variable = '';
}
parent::bindParam($parameter, $variable, $data_type, $length, $driver_options);
}
}
在插入或更新时,我正在这样做
$insertUser = $pdoDB->prepare("INSERT INTO users (id,email,name,age) VALUES (:id, :email, :name, :age)");
$insertUser->removeNulls = TRUE;
$insertUser->bindValue(':id', $id);
$insertUser->bindValue(':email', $email);
$insertUser->bindValue(':name', $name);
$insertUser->bindValue(':age', $age); // May be NULL
$insertUser->execute();
通过将array 作为参数传递给execute(),避免对removeNulls 绑定值进行过多检查。
通过参考以下来源得到这个想法
-
Extending PDO class。
-
Extending PDOStatement class 和 this。
- 其他网络来源。