Assuming you have it all in $data
array:
$query_string = "insert into mytable set a=1, b=2, d1=" .
(isset($data['val1']) ? "'" . $data['val1'] . "'" : 'NULL') . ", d2=" .
(isset($data['val2']) ? "'" . $data['val2'] . "'" : 'NULL') . ", d3=" .
(isset($data['val3']) ? "'" . $data['val3'] . "'" : 'NULL') . ";";
The string will contain eg. d2=NULL
instead of d2='xyz'
, if the value in array does not exist or is equal to null
.
You have to also make sure that the strings you want to paste into the query are properly sanitized (eg. using mysql_real_escape_string()
). My answer treats your variables as already prepared and sanitized, as you only wanted to know how to insert NULL
values instead of the variables you have.
Because the question was only about entering NULL
values in the query based on the value of variables, I do not think discussing sanitization in detail here would be a good idea. You can find a lot more detailed info on SQL Injection and how to prevent it in PHP here: Best way to stop SQL Injection in PHP. Good luck! :)