I have an html form used to edit a record in a mysql table.
In the case of editing, I prefill the form with the current values for the record as returned by the query, as below:
<INPUT TYPE="text" NAME="SITENAME" SIZE=35 VALUE="<?php echo $customer['sitename']; ?>">
I would like to use the same form for creating a new record, but of course there would be no values assigned to the sql query array, and as such the form would not work.
I know I could put an IF or ISSET for every input, or a single one but then have to duplicate the form code without each echo statement. Both seem cumbersome.
Is there a better way to use the same form code?
2
Answers
I think that the most compact way is:
Additionally, You should sanitize the value, it can contain harmful characters like
"
:The null coalesce operator is perfect for this situation. It’s basically shorthand for
if(isset())
:You’re thinking of doing something like this:
This can be shortened to:
And since you want nothing in the default case, you can just use
null
:I.e., output the existing sitename if you have it, else nothing. And note you can use the short open syntax if all you’re doing is echo, so your code becomes: