简体   繁体   中英

How to insert empty string instead of null in PHP PDO

I'm refactoring the code, from mysql extension to pdo's . Existing db schema is such way that for almost all columns in 100 pulse tables are having NOT NULL constraint. Due to this constraint I'm very often facing following error while inserting and updating the data.

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

Obligations:

  1. Its not possible to change db schema i,e removing NOT NULL constraint.
  2. Its difficult to check whether value is null or not before inserting for each and every column.

So I'm looking for a generic solution where empty string is inserted instead of NULL that will be addressed for all PDO statements. I'm using this PDO helper class.

When you declare your column, do it with NOT NULL DEFAULT '' . This way, MySQL will replace a NULL value with an empty string.

After searching in web finally come with following solution by extending PDOStatement class. Remember this credits goes SE and other sources in web.

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

And while inserting or updating I'm doing like this

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

To avoid too many checks for removeNulls bind values by passing array as argument to execute() .

Got this idea by referring following sources

  1. Extending PDO class .
  2. Extending PDOStatement class and this .
  3. Other sources of web.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM