【问题标题】:How to insert empty string instead of null in PHP PDO如何在 PHP PDO 中插入空字符串而不是 null
【发布时间】:2015-12-16 12:15:33
【问题描述】:

我正在重构代码,从 mysql 扩展名到 pdo's。现有的db 模式是这样的,即对于 100 个脉冲表中的几乎所有列都具有NOT NULL 约束。由于这个限制,我经常在inserting 和updating 数据时遇到以下错误。

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'some-column-name' cannot be null

义务:

  1. 无法更改数据库架构,即移除 NOT NULL 约束。
  2. 在插入每一列之前很难检查值是否为空。

所以我正在寻找一个通用的解决方案,其中插入空字符串而不是 NULL,它将为所有 PDO 语句解决。我正在使用 this PDO 助手类。

【问题讨论】:

  • 你能举个例子说明你是如何插入数据的吗?

标签: php mysql pdo null constraints


【解决方案1】:

当您声明您的专栏时,请使用NOT NULL DEFAULT ''。这样,MySQL 将用空字符串替换 NULL 值。

【讨论】:

  • 感谢您的回复,但正如我在“义务”部分中提到的,无法更改数据库架构。
【解决方案2】:

在网上搜索后,通过扩展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 绑定值进行过多检查。

通过参考以下来源得到这个想法

  1. Extending PDO class。
  2. Extending PDOStatement class 和 this。
  3. 其他网络来源。

【讨论】:

    猜你喜欢
    • 2011-06-04
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2022-01-19
    • 2012-12-06
    • 2019-07-06
    • 2017-08-01
    相关资源
    最近更新 更多