I am creating a form and am just looking for more efficient ways to do things. What I have so far is:
<p><input type="text" name="transmission" value="" /></p>
<p><input type="text" name="model" value="<?=$model;?>" /></p>
So some of them will have a value already set, and some will be blank. What I want to do is see if the form has been set, and if it has then use $_POST['name'] as the value, if not then use either blank or use the previous variable I have.
<p><input type="text" name="name" value="<?php if isset($_POST['submit'])) { echo $_POST['name']; } else { echo ""; } ?>" /></p>
But there has to be a shorter way to do that.
IF anyone could point me in the direction I would really appreciate it.
Thank you!
isset( $_POST['submit'] ) : This line checks if the form is submitted using the isset() function, but works only if the form input type submit has a name attribute (name=”submit”).
The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.
Use isset() method in PHP to test the form is submitted successfully or not. In the code, use isset() function to check $_POST['submit'] method. Remember in place of submit define the name of submit button. After clicking on submit button this action will work as POST method.
The equivalent of isset($var) for a function return value is func() === null . isset basically does a !== null comparison, without throwing an error if the tested variable does not exist.
You can define variables in beginning of your script before HTML output, for example:
$name = isset($_POST['submit']) ? $_POST['name'] : null;
in your html section you can print $name without worrying it was not defined
<p><input type="text" name="name" value="<?php echo $name ?>" /></p>
Also if $_POST['submit'] does not contain any value you are more likely to receive FALSE statement. To avoid such issues use array_key_exists
Like Nazariy said, you should avoid as much PHP in the template as possible.
In fact, you should have in your template already prepared variables only.
So, in your code have something like this
$FORM = array();
$form_fields = array('name','sex');
foreach($form_fields as $fname) {
if (isset($_POST[$fname])) {
$FORM[$fname] = htmlspecialchars($_POST[$fname]);
} else {
$FORM[$fname] ='';
}
}
and then you have smooth and neat template:
<p><input type="text" name="name" value="<?=$FORM['name']?>" /></p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With