PHP/MySQL Insert null values?

This is one example where using prepared statements really saves you some trouble.

This is one example where using prepared statements really saves you some trouble. In MySQL, in order to insert a null value, you must specify it at INSERT time or leave the field out which requires additional branching: INSERT INTO table2 (f1, f2) VALUES ('String Value', NULL); However, if you want to insert a value in that field, you must now branch your code to add the single quotes: INSERT INTO table2 (f1, f2) VALUES ('String Value', 'String Value'); Prepared statements automatically do that for you. They know the difference between string(0) "" and null and write your query appropriately: $stmt = $mysqli->prepare("INSERT INTO table2 (f1, f2) VALUES (?,?)"); $stmt->bind_param('ss', $field1, $field2); $field1 = "String Value"; $field2 = null; $stmt->execute(); It escapes your fields for you, makes sure that you don't forget to bind a parameter.

There is no reason to stay with the mysql extension. Use mysqli and it's prepared statements instead. You'll save yourself a world of pain.

Brilliant, thanks i'm now a mysqli convert! – MattP Mar 17 at 10:40.

I think you need quotes around your {$row'null_field'}, so '{$row'null_field'}' If you don't have the quotes, you'll occasionally end up with an insert statement that looks like this: insert into table2 (f1, f2) values ('val1',) which is a syntax error. If that is a numeric field, you will have to do some testing above it, and if there is no value in null_field, explicitly set it to null..

Thanks, i'll have to add some additional testing and explicitly set the nulls, it is much more logical in the application that the fields are null rather than empty strings. – MattP Mar 16 at 18:04.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions