Jump to content

Mysql and NULL values


leony

Recommended Posts

Hello,

 

I have an HTML form and it collects customer address, tel no, post code etc...However all these fields are not required as in the following:

 

<select name="contact">
                <option value="0" selected="selected">Select</option>
                <option value="1">Yes</option>
                <option value="2">No</option>
              </select>

 

If the customer does not select anything, I want to insert a NULL value to the database, because, I cannot get it right, instead of NULL value, I have to use a ZERO (0) value.

 

INSERT INTO table (first_name, last_name, house_no, street, city, county, postcode, email, phone, contact insert_date) VALUES ('$first_name', '$last_name', '$house_name', '$street', '$city', '$county', '$postcode', '$email', '$telephone', $contact, NOW())";

 

There are lots of 0s in the database and somehow I want to insert NULL value instead of zero. How can it be done?

 

Thanks...

 

Link to comment
https://forums.phpfreaks.com/topic/142814-mysql-and-null-values/
Share on other sites

if(empty($contact))
  $contact = 'NULL';

  $sql = "INSERT INTO table (first_name, last_name, house_no, street, city, county, postcode, email, phone, contact insert_date) VALUES ('$first_name', '$last_name', '$house_name', '$street', '$city', '$county', '$postcode', '$email', '$telephone', $contact, NOW())";

 

if(empty($contact))
  $contact = 'NULL';

  $sql = "INSERT INTO table (first_name, last_name, house_no, street, city, county, postcode, email, phone, contact insert_date) VALUES ('$first_name', '$last_name', '$house_name', '$street', '$city', '$county', '$postcode', '$email', '$telephone', $contact, NOW())";

 

 

Hi,

 

For your sample code, I have noticed that as long as the contact value is NULL, the query is executed , however if it is not, I get an error message.

 

The column is NULL meanwhile.

 

Thanks...

is $contact a number? try this instead:

$contact = empty($contact) ? 'NULL' : "'".mysql_real_escape_string($contact)."'";

  $sql = "INSERT INTO table (first_name, last_name, house_no, street, city, county, postcode, email, phone, contact insert_date) VALUES ('$first_name', '$last_name', '$house_name', '$street', '$city', '$county', '$postcode', '$email', '$telephone', $contact, NOW())";

 

edit: and if that doesn't work...when the query fails what is the error outputted by mysql_error() ?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.