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?

5 Answers 5

2

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

function IsEmptyString($val){
    if (trim($val) === ''){$val = "NULL";}
    return $val;
}
Sign up to request clarification or add additional context in comments.

2 Comments

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).
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
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.

Comments

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;

Comments

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

1 Comment

@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.
0

Looks like a good candidate for a ternary operator:

function valOrNull($val) {
    return (trim($val) === '') ? NULL : $val;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.