2

I am trying to find a solution to achieve the following result.

If MySQL query has empty string '', than use default value defined in a table schema.

For example

INSERT INTO `users`(`name`,`nickname`,`balance`) 
VALUES ('hello','world','');

In this case if the balance column's default value is 0 then it should be set instead of the empty string.

Is it possible to achieve this ?

Dharman
  • 30,962
  • 25
  • 85
  • 135

2 Answers2

0

A better way would be to create a trigger. Read more about the triggers on Mysql documentation. Similar answer for more details can be found here.

For this question here is my implementation of the trigger.

delimiter #
create trigger nonEmptyString
before insert
on users
for each row

BEGIN
IF NEW.balance = '' THEN
   SELECT COLUMN_DEFAULT INTO @def
   FROM information_schema.COLUMNS
   WHERE
     table_schema = 'Schema Name'
     AND table_name = 'users'
     AND column_name = 'balance';
   SET NEW.balance = @def;
END IF;

end#

delimiter ;

Note : Replace Schema Name with the name of your schema.

Chandan Purbia
  • 285
  • 4
  • 14
  • You can use the [DATABASE()](https://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_database) function instead of `Schema Name`. – wchiquito Jun 23 '17 at 11:26
0

use a variable (such as $balance) instead of '' (which I expect you'd be doing anyway).

On the line before your query:

if(strlen(trim($balance))==0){ $balance='0'; }

You could also use the mysql case syntax, which is a bit clunky, but very much on point for your description.

MySQL update CASE WHEN/THEN/ELSE

TheSatinKnight
  • 696
  • 7
  • 16