I have some columns type int, but value is empty. So I want to convert empty to null when I insert to database. I use code:
function toDB($string) {
if ($string == '' || $string == "''") {
return 'null';
} else {
return "'$string'";
}
}
//age,month,year is type integer.
$name="Veo ve";
$age='10';
$month='';
$year='';
$query="Insert Into tr_view(name,age,month,year) values ({toDB($name)},{toDB($age)},{toDB($month)},{toDB($year)})
$db->setQuery($query);
$result= $db->query();
But it show error:
pg_query(): Query failed: ERROR: syntax error at or near "{" LINE 153: {toDB(10)}, ^ in...
Why?
While Erwin's answer about
NULLIF
is awesome, it doesn't address your syntax error.Let's take a look at the query:
Earlier you defined a function called
toDB
. Unfortunately the syntax you are using here is not how to call a function from within a double-quoted string, so the curlies andtoDB(
bits are still being passed through. There are two alternatives:Concatenation using
.
:You can interpolate a callable variable into a double-quoted string thusly:
The first is clear and sane, the second is vague to the unfamiliar and downright insane.
However, you still should not be assembling input like this. You still may be vulnerable to SQL injection attacks. You should be using prepared statements with parameterized placeholders.
The Postgres extension uses
pg_prepare
for this. They have the distinct advantage of, say, allowing you to pass a PHPnull
instead of having to worry about all of that null-detection and quoting.If you insist on keeping
toDB
as-is, consider adding one of thepg_escape_
functions, likepg_escape_string
, to the thing that builds quoted strings.There is the
NULLIF()
function:If
var
holds the value in $2, you getNULL
instead.In the example I replace the empty string:
''
withNULL
.There is no empty string for the type integer. Just not possible. Since
NULLIF()
cannot switch the data type, you have to sanitize your input in PHP.If you did not define a column default, you can also just omit the column in the
INSERT
command and it will be filled withNULL
(which is the defaultDEFAULT
).Check if the parameter is empty in PHP and don't include the column in the
INSERT
command if it is.Or use the PHP literal NULL instead like Quassnoi demonstrates here.
The rest only makes sense for string types
To make absolutely sure, nobody can enter an empty string add a
CHECK
constraint to the table:To avoid exceptions caused by this, you could add a trigger that fixes input automatically: