capitalistpug capitalistpug - 1 month ago 9
MySQL Question

Function to Make Empty String NULL for MySQL Insertion in PHP

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?

Answer

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

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