简体   繁体   中英

PHP Mixing server code with HTML output

I'm coding up a small script that'll take form data and do something with it. If it fails, it shows the error and the form again. If it succeeds, it'll show a success message.

The backend code is using classes that'll throw exceptions if there's an error with the form data. The calls to the classes will be wrapped in a try{} catch{}.

What would be the best way to show the form twice?

I need something like:

If form submitted: 

   Try:
      Add the account via class
   Catch:
      Echo the error
      Show the form 

   Echo succcess

Else:
   Show the form

For simple forms, I wrote like this:

<?php

   if (isset($_POST['submit']))
   {
   $errorFound=0;

   if (empty($_POST['form_variable']))
   { 
     $errorFound=1; 
     $error_str="empty string";
   }

   if (!$errorFound) // if no errors, process the form!
   { 
   //process whatever you do with it - redirect to another page
   }

  }
 ?> 
 <form action="name.php">
 <div> <input name='form_variable'> 
 <?php if ($errorFound) {echo $error_str} ?>
 </div> 
 <input type=submit name=submit>
 </form> 

What happens is that if it's never submitted, it will go straight to html form and display but if you submitted and there is an error, it will cause php to display the form again with the echo'd error_st after the input tag.

Encode the HTML for the form in a variable, and echo out the variable at both locations.

$form = "<form>...</form";

if ($_POST) {
  if (addAccount($fname,$email)) {
    print "Success";
  } else {
    print "Errors";
    print $form;
  }
} else {
  print $form;
}

You can do all these stuff very easily with smarty like template engine. Its just exactly same as your question

{If $form eq submitted)}

{if $success} Add the account via class {else} Echo the error Show the form

Echo succcess {/if} {else} Show the form {/if}

Or if you just want to do it in php alone means just do the "netrox" method. Its good.

and these is another concept call heredoc in php. you can include your html in php in very easier way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM