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
- Extending PDO class.
- Extending PDOStatement class and this.
- Other sources of web.