Skip to content
Advertisement

Why Inserting a value in a nullable field from a HTML FORM gives me a NULL even if it is not?

I created a database with a table that contains both mandatory and nullable fields. When I insert mandatory fields everyhing works fine, but when I try to insert a value in a field that is optional and can be NULL i always get a NULL result when checking the database. Here’s the code: (user_id is mandatory and username is optional. Whether I type something in username or not I always get a NULL in the corresponding db field.

JavaScript

Thank you for your help

Advertisement

Answer

Your code is performing two INSERT queries. eEach INSERT will create a new row, but the query that inserts only the username will fail because the user_id is set NOT NULL. Hence. you see one rwo with just the user ID and no user name.

You need to insert both fields in one INSERT, so, in the context you ask the question do this (but see below):

JavaScript

Important: The solution above is vulnerable to SQL injection. mysql_*() is also an archaic interface to MySQL – it was removed from PHP7 some years ago. You’d do better using PDO which also allows you to use prepared statements. The PDO version of this is:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement