While Erwin's answer about NULLIF
is awesome, it doesn't address your syntax error.
Let's take a look at the query:
$query="Insert Into tr_view(name,age,month,year) values ({toDB($name)},{toDB($age)},{toDB($month)},{toDB($year)})
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 and toDB(
bits are still being passed through. There are two alternatives:
Concatenation using .
:
$query='insert Into tr_view(name,age,month,year) values (' . toDB($name) . ',' . toDB($age) . ',' . toDB($month) . ',' . toDB($year) . ')')
You can interpolate a callable variable into a double-quoted string thusly:
$fn = 'toDB';
$query="Insert Into tr_view(name,age,month,year) values ({$fn($name)},{$fn($age)},{$fn($month)},{$fn($year)})";
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 PHP null
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 the pg_escape_
functions, like pg_escape_string
, to the thing that builds quoted strings.