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?
The null coalesce operator is perfect for this situation. It’s basically shorthand for if(isset())
:
You’re thinking of doing something like this:
if (isset($customer['sitename'])) {
echo $customer['sitename'];
} else {
echo $someDefaultValue;
}
This can be shortened to:
echo $customer['sitename'] ?? $someDefaultValue;
And since you want nothing in the default case, you can just use null
:
echo $customer['sitename'] ?? 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:
<INPUT TYPE="text" NAME="SITENAME" SIZE=35 VALUE="<?= $customer['sitename'] ?? null; ?>">
1
I think that the most compact way is:
value="<?php echo $customer['sitename'] ?? ''; ?>"
Additionally, You should sanitize the value, it can contain harmful characters like "
:
value="<?php echo htmlspecialchars($customer['sitename'] ?? ''); ?>"