Help with inserting null values in postgres database

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
pavlosli
Forum Newbie
Posts: 1
Joined: Mon Mar 31, 2008 9:40 pm

Help with inserting null values in postgres database

Post by pavlosli »

Hi,

I have a postgres database, and the table customer keeps some data, such as first name, last name, tel, email, etc.

Now I'm building a web application and I want to insert values into the above table.
So I made a form so the user can enter the data.
And then a query
$query = "insert into customer (first_name, last_name, tel1, tel2, mobile, email) values ('".$_POST['first_name']."', '".$_POST['last_name']."', '".$_POST['tel1']."', '".$_POST['tel2']."', '".$_POST['mobile']."', '".$_POST['email']."');

tel1, tel2, mobile are numeric in the database.

When I leave a field blank in the input fields, I want a null value in the database!! But this doesn't seem to happen.

Any ideas?
Thanx in advance
User avatar
EverLearning
Forum Contributor
Posts: 282
Joined: Sat Feb 23, 2008 3:49 am
Location: Niš, Serbia

Re: Help with inserting null values in postgres database

Post by EverLearning »

First, using $_POST values directly in a BIG security risk, especially since you say that this is a form that will users use to enter data. Escape data before you enter it into database

Code: Select all

$fname = pg_escape_string($_POST['first_name']);
$lname = pg_escape_string($_POST['last_name']);
and then use those variables in SQL statement

Even better - use prepared statements.

As for the NULL values, are you sure fields in database are not defined NOT NULL?
You can't quote variables in the statement, since it will then insert 'NULL' as string, so you'll need to add the quotes earlier

Code: Select all

$fname = if trim($_POST['first_name']) != '' ? "'" . pg_escape_string($_POST['first_name']) . "'" : 'NULL';
.

This is all untested code, so if there's any problem, ask.
Post Reply