Jump to content

[SOLVED] Make blank form fields always send NULL to MySQL


pakenney38

Recommended Posts

Say I've got a form variable set to a new variable like so:

$newvar = $_POST['newvar'];

If the newvar form field contained no value, is there any way to prevent PHP from sending $newvar as '' in a MYSQL statement and instead send a NULL value for $newvar?

Well ideally, I would like to just do something like

$query = "INSERT INTO table (blah1, blah2, blah3, newvar) VALUES ($blah1, $blah2, $blah3, $newvar)";
mysql_query($query);

But if the form field associated with $newvar was not filled in, I would like it to not submit a value to MySQL. If there is some easy way of doing this without going through the whole

if ($newvar != '')

before I run my query, then I would like to know how to do that. I suppose I could just use $_POST['newvar'] in my MySQL query, but in my situation, I can't always do it that way.

This is obviously my first exposure to the ternary operator in PHP, but I love it.

What I needed was something like this:

$newvar = (empty($_POST['newvar'])) ? NULL : $_POST['newvar'];

Just knowing that the ternary operator exists is going to make my life so much easier.

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.