-1

Is there any better way to achieve the same result, by using PHP externally instead of inside the actual HTML tag? This method works fine, but it seems a little inconvenient to place PHP tags inside HTML tags like this. Especially when you have to adjust multiple attributes when submit is clicked. Or worse, multiple attributes of multiple elements in the same form!

As an absolute PHP beginner I have no clue...

<form method="post" action="">
  <input type="text" name="input" value="
    if (isset ($_POST['submit']) ) {
      $input = $_POST['input'];
      echo $input;
    }
  " />
  <input type="submit" name="submit" />
</form>

Please note: The script above may be faulty, because I wrote it directly into this forum post without testing it externally. I am merely trying to point out the idea of it: Adjusting the style, value or any other attribute using PHP only.

Al John
  • 612
  • 5
  • 24
  • You could use a ternary operator to make that a lot shorter. And yes alternatively you could do most of the processing elsewhere and just echo the variable within the PHP. To get more advanced you should perhaps investigate the various templating engines available too. – ADyson Jul 18 '21 at 09:46

2 Answers2

2

If you don't want to put your PHP logic in your HTML code, you could write the php logic above the HTML code and store the result in a variable which you can then put in the HTML code.

For example:

<?php 
$input = '';
if (isset ($_POST['submit']) ) {
  $input = $_POST['input'];
} 
?>
<form method="post" action="">
 <input type="text" name="input" value="<?php echo $input; ?>" />
 <input type="submit" name="submit" />
</form>
RyDog
  • 1,169
  • 1
  • 9
  • 12
0

If you need to make your code shorter you can use short tags

<form method="post" action="">
  <input type="text" name="input" value="<?= isset ($_POST['submit']) ? $_POST['submit'] : '' ?>" />
  <input type="submit" name="submit" />
</form>

You may provide all you need before rendering

<?php
    $html = [
         'forms' => [
              'myForm' => [
                    'action' => '',
                   'method' => 'POST',
                   'myInput' => [
                        'value' => isset ($_POST['submit']) ? $_POST['submit'] : ''
                    ],
              ],
         ],
    ];
?>
<form method="<? $html['forms']['myForm']['method'] =?>" action="<?= $html['forms']['myForm']['method'] ?>">
  <input type="text" name="input" value="<?= $html['forms']['myForm']['myInput']['value'] ?>" />
  <input type="submit" name="submit" />
</form>

Also there is some tools so you can use php within your html more readable. Using PHP as a template engine

Debuqer
  • 328
  • 2
  • 7