0

I'm trying to insert null into a postgres database with php. Say I have this:

<?php
$sql = <<<EOT
insert into
    t1
(c1, c2)
values
($param, 'test')
EOT;
?>

I tried setting $param to:

$param = null;
$param = '\N';

and in each case I got this error:

Native message: ERROR:  syntax error at or near ","

What do I need to set it to?

1
  • 1. Prepared statements. 2. NULL. Commented May 21, 2021 at 23:58

3 Answers 3

2

You can do it using parameters.

Either with PDO:

$query = "INSERT INTO t1 VALUES(?,?)";
$insertStatement = $pdo->prepare($query);
$insertStatement->execute([null, 'test']);

Execute PHP online

of with pgsql functions

pg_query_params($dbconn, 'INSERT INTO t1 VALUES($1,$2)', [null, 'test']);
Sign up to request clarification or add additional context in comments.

Comments

1
$param = 'null';

it should work.

Comments

-1

The way you deal with null depends on type of the fields and the syntax of the query. Suppose you write the following query:

UPDATE table SET fld_char='$fld_char', fld_int=$fld_int WHERE id=0

Then you can set the variables as these:

fld_char = null;
fld_int = 'null';

You will have fld_int as null and fld_char as empty.

5 Comments

so you failed to answer how to insert fld_char as null. not to mention that you should NEVER have $fld_char or $fld_int in your query. Learn about prepared statements
if I leave $fld_char or $fld_int in the query which thing is allowed though not recommended, how can I have fld_char NULL?
You just DON'T have them in the query. Problem solved
I agree on prepared statements but look at the accepted answer which shows the OP requirement.
I did look at that bad answer. So what?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.