Jump to content
Larry Ullman's Book Forums

Chapter 19 - Adding Null Value To Database Not Working.


Recommended Posts

When using the add_print.php script, if I add a description to the description field, the database inserts the string value. However, when I don't enter a description, instead of inserting NULL, an empty value is inserted. So when I view a specific print that does not have a description, no message is displayed. If I go into my database and manually change the empty description field to NULL and redisplay the print page, my (No description) message is shown. Any ideas why this is happening.

 

My check for description:

$d = (!empty($_POST['description'])) ? trim($_POST['description']) : NULL;

 

My query:

$q = 'INSERT INTO prints (artist_id, print_name, price, size, description, image_name) VALUES (?, ?, ?, ?, ?, ?)';
        $stmt = mysqli_prepare($dbc, $q);
        mysqli_stmt_bind_param($stmt, 'isdsss', $a, $pn, $p, $s, $d, $i);
        mysqli_stmt_execute($stmt);

Link to comment
Share on other sites

Hmmm...I thought that's what my conditional was doing:

$d = (!empty($_POST['description'])) ? trim($_POST['description']) : NULL;

 

Just for kicks I revised the above to:

$d = (!empty($_POST['description']) || ($_POST['description'] != ' ')) ? trim($_POST['description']) : NULL;

 

and:

if (empty($_POST['description']) || ($_POST['description'] == '')) {
        $d = NULL;
    } else {
        $d = trim($_POST['description']);
    }

 

Both with the same results, NULL has not been inserted into database.

Link to comment
Share on other sites

Thank you for your help in troubleshooting this.

 

When I used $d = NULL without any conditionals it worked.

 

After some google searches I found a solution. It seems that because the description is in a textarea on a form, it behaves differently than an input of type "text". So to get it to work, I can't just check if the textarea is empty. The simple existence of the textarea means it will always have a value, even if that value is an empty string. The only way textarea would be NULL is if the box itself was not instantiated for whatever reason.

 

So both of these will work for me...

if (strlen(trim($_POST['description'])) == 0) {
		$d = NULL;
	} else {
		$d = $_POST['description'];
	}

or

if (trim($_POST['description']) == '') {
		$d = NULL;
	} else {
		$d = $_POST['description'];
	}

From there I can shorten the code to

$d = (trim($_POST['description']) == '') ? NULL : trim($_POST['description']);

I guess this makes sense to me. Does this sound legit to you?

Link to comment
Share on other sites

 Share

×
×
  • Create New...