Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 854
Mahesh.D Avatar asked Sep 01 '26 03:09

Mahesh.D


1 Answers

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

like image 67
Richard St-Cyr Avatar answered Sep 03 '26 15:09

Richard St-Cyr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!