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;
W开发者_JAVA百科hat am I doing wrong? Also should I call the function before escaping?
You need to return $val at the end of the function:
function IsEmptyString($val){
if (trim($val) === ''){$val = "NULL";}
return $val;
}
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.
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;
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';
}
Looks like a good candidate for a ternary operator:
function valOrNull($val) {
return (trim($val) === '') ? NULL : $val;
}
精彩评论