Jump to content

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


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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.