I want to insert data in my DB, but first I want to check if the field is empty, if it is, I want to replace it; change : ''
to null
, but it doesn't, it keeps leaving it as an empty string , that is: ''
.
This comes from the form:
$fecha_nacimiento= $_POST['fecha_nacimiento'];
So I do the following:
if (strlen(trim($fecha_nacimiento)) == 0) {
$fecha_nacimiento = null;
}
Doing echo
a strlen(trim($fecha_nacimiento))
sample 0
. But it does not go through the if
one I have put.
I want to do this because I have a variable $sql
with the insert, and if it goes through the if I put it to null and if not what I receive.
I receive the dates from input
a type : date
.
$sql = "INSERT INTO familiares(fecha_nacimiento) VALUES('".$fecha_nacimiento ."');";
The thing is that it gives an error if I insert a string without DATE format in the DB. For what I wanted to control with an if that tells me, if it is ( .length == 0
) that I put it in null
. But it doesn't.
CLARIFICATION : The error is not that it puts 'NULL'
instead of NULL
and detects it as a string, but rather that var_dump()
it (whether .length == 0
or not) always returns ''
.
The
if
one you have suggested works fine. With an empty string the variable$fecha_nacimiento
will be set to valueNULL
.The problem is elsewhere. More specifically in
insert
:When you try to print the value of a variable whose value is
NULL
you won't get the wordNULL
, since variables of this type don't have conversion tostring
, as do variables of typeboolean
, so what youinsert
're really doing:Without seeing the rest of your code, a possible solution would be the use of prepared statements , which would allow you to pass
querie
a variable with a value toNULL
it and also make your application more secure by controlling SQL injection.I see no way to fail the
if
; unless it's a special character, which you could check withmb_strlen
. Maybe the problem is in the after handling.The rules are:
trim(null) = ''
andisset('') = true
.Therefore:
isset(trim(null)) = true
.I ask the question: Do you do that so that in your table the null fields look like this?
because that is achieved by defaulting to NULL in the field