I have input fields, but if the users leave it blank, i want to insert a null value to my database.
I request values like this:
$val1 = htmlspecialchars($_REQUEST["val"], ENT_QUOTES);
And then insert them to the DB:
INSERT INTO `table` ( `val1` , `val2` , `val3`)
VALUES ('$val1', '$val2', '$val3');
I have tried removing the ‘ around val1, val2, val3 – but then nothing gets inserted into the DB if there is no value. I have also tried something like this:
if (!empty($val1)) {
$val1 = "'".$val1."'";
} else {
$val1 = NULL;}
And then without the ‘ around the values – still no insert to the DB
Ok, first this
will only ever insert the literal values “val1”, “val2” and “val3”. You aren’t using any PHP variables.
Secondly, use prepared statements and parameter binding to perform your queries to protect yourself from SQL injection. For example, using PDO
Also, you shouldn’t HTML encode values going into a database. Perform the encoding when you display the value in an HTML document.