0

This is similar question to MySQL and PHP - insert NULL rather than empty string but I'm still encountering the problem.

I'm trying to create a function so that an empty string is inserted as a NULL into MySQL.

I create the function IsEmptyString:

function IsEmptyString($val){
    if (trim($val) === ''){$val = "NULL";}
}

Before inserting the the variable, I escape it and then I call the function above. I've also tried $val = NULL;

What am I doing wrong? Also should I call the function before escaping?

Community
  • 1
  • 1
Kamil Sindi
  • 21,782
  • 19
  • 96
  • 120

5 Answers5

2

You need to return $val at the end of the function:

function IsEmptyString($val){
    if (trim($val) === ''){$val = "NULL";}
    return $val;
}
psx
  • 4,040
  • 6
  • 30
  • 59
  • I tried that but have the same problem. Can I just call the function, e.g. `IsEmptyString($name)` or do I have to set `$name = IsEmptyString($name)`. – Kamil Sindi Oct 13 '11 at 14:17
  • You need to call $name = IsEmptyString($name). Another option is to define the function as: function IsEmptyString(&$val) then you do not need to return the value – psx Oct 13 '11 at 14:18
0

Looks like a good candidate for a ternary operator:

function valOrNull($val) {
    return (trim($val) === '') ? NULL : $val;
}
Nathan Arthur
  • 8,287
  • 7
  • 55
  • 80
0

You're not returning the value. This should work

function IsEmptyString($val){
    if (trim($val) === ''){$val = "NULL";}
return $val;
}

Also you're assigning your variable to a string and not null.

This line $val = "NULL";

should be

$val = null;

Also see PHP's isset() and empty() functions.

Mob
  • 10,958
  • 6
  • 41
  • 58
0

Either you can return the result with return...

function IsEmptyString($val)
{
  if (trim($val) === '')
    return 'NULL';
  else
    return $val;
}

...or you have to pass the variable as reference (note the & before the $val)

function IsEmptyString(&$val)
{
  if (trim($val) === '')
    $val = 'NULL';
}
martinstoeckli
  • 23,430
  • 6
  • 56
  • 87
  • @Rufinus - It seems that the OP is using the string 'NULL' to build an SQL statement. The function is a modification of the given example, it has other flaws too, as a misleading name for example. – martinstoeckli Nov 12 '15 at 08:07
0

alternativly, you can pass val as reference.

function IsEmptyString(&$val){
    if (trim($val) === ''){$val = "NULL";}
}

however, be carefull not to send "'".$val."'" to the database;

roselan
  • 3,755
  • 1
  • 20
  • 20