tags:

views:

159

answers:

7

I'm creating a FORM with PHP for an intranet webpage. Another PHP script is called by submitting the form.

Before anyone asks, the form does not allow any uploads, and although the values entered in the form find their way into an SQL query, I strip out everything but numbers.

I'm wondering if there would be a advantage in using the same PHP file for both the FORM and the ACTION?

Obviously, increased complexity is the penalty — ie, figuring out, when invoked, if the FORM is to be created, or if the SUBMIT button has been clicked — but what would be the benefits?

EDIT: Note, the PHP in 'submit' mode does not redisplay the form, it does something entirely different. This is the source of the complexity I was worried about.

The form is used to enter values which are checked against values in a DB, but there are no changes made to the DB.

A: 

Well, mainly if you want to re-show the form to the users without loosing data, then you can just write something like this:

<input type="text" name="myInput" value="<?php
    echo htmlspecialchars(isset($_POST["myInput"]) ? $_POST["myInput"] : "");
?>">


Update: here is an example of this method:

<?php
$error = "";
$result = "";

$a = isset($_POST["a"]) ? $_POST["a"] : "";
$b = isset($_POST["b"]) ? $_POST["b"] : "";

if ($a !== "" && $b !== ""){

if (is_numeric($a) && is_numeric($b))
    $result = sprintf("%s + %s = %s", $a, $b, $a + $b);
else
    $error = "You must enter two numbers!";

}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
<html>
<head><title>Sum numbers</title></head>
<body><form method="post" action="<?php print htmlentities($_SERVER["REQUEST_URI"]); ?>">
<p><strong>Enter two numbers to add them together.</strong></p>
<?php if ($error){ printf ("<p><em>%s</em></p>", htmlspecialchars($error)); } ?>
<p>
    <input type="text" name="a" value="<?php print htmlspecialchars($a); ?>">
    +
    <input type="text" name="b" value="<?php print htmlspecialchars($b); ?>">
    <input type="submit">
</p>
<?php if ($result){ printf("<p><strong>%s</strong></p>", htmlspecialchars($result)); } ?>
</form></body>
</html>
MiffTheFox
+2  A: 

I tend to find it more maintainable to have the php that creates the form separate from the php that is called by the form.

It will also reduce (though it isn't noticeable) one if statement to determine if this is a form request or filling in the form.

But, the problem is that unless you are going to take them to a new page, you will have to get the values back into the form which can be more complicated.

So, if you want to keep the values in the form, even after the form is processed, then leave the form processing logic at the beginning of the file, otherwise I would opt for maintainability and have them in two files.

James Black
I tried in the past to combine the scripts, and it worked, but at the cost of maintainability. I'm not worried about keeping the values in the form, except when a mistake is made and discovered at submission. The users *shouldn't* have to re-enter all values before trying again. The *maintainability* approach is easiest because I don't have to make any changes to my present method.
pavium
+1  A: 

In most case, I prefer that.

Keeping both together make the code more 'cohesive' as the code of accepting value (via form) is in the same php file (called it View and Control). To me this is an advantage.

However, the code that manipulate database should be separated in other file as it not the same as accepting value (called it a model library). This make it less-coupling as accepting and manipulation is separated. This decoupling will reduce the complexity you are worrying about.

Another advantage of is the URL. The users will see it as from the same page.

However, this is totally depends on your overall system metaphor and work flow. For example, it make better sense to the users that addBook.php handle book adding form and show that the adding has success or fail. Comparing that too having two addBook.php, addBookProcess.php.

What I am trying to say is that the flow of pages should be a more important factor to determine if you want to separate or combine them. Decoupling interface/logic code will helps you reduce the complexity if pages need to be combine into one php file.

Just my though.

NawaMan
Things are going well: *this* is good, but *that* is good also. The answers so far reflect my thoughts entirely, which makes me think I'm not doing something terrible. Incidentally, the values entered in the form are used to locate DB entries for comparison. None of it results in changes to the DB.
pavium
+1  A: 

Form is about user interface, action is about doing something with data. The part of code that actually processes user input must certainly be separate from the form structure. The form code must accept default values (or values previously entered and found to be invalid), error messages etc. It must have nothing to do with usage of successfully submitted form data. If you allow user to change invalidated input, then you must have action URL the same as form. If successful submission leads to something unrelated, then its URL must be different from that of the form. Basically, you must redirect user from the URL where the form got accepted to the next URL.

If you're doing AJAX, none of this applies.

zilupe
I don't think the situation is quite so *black and white*. Why **must** URLs be different on successful submission? Most users don't pay any attention to URLs, anyway. But I agree that the separation of user interface and results is a logical division and probably worth keeping. Users can re-enter invalidated input by simply hitting 'back' and trying again.
pavium
You're right. My use of 'must' is inappropriate here. Not a native English speaker.
zilupe
A: 

It depends!

The upside to having them in one file is that it puts a single block of functionality into one place and allows you to handle form validation. The downside is increased complexity. It really starts to suck if you have the markup for both pages in one file.

I would suggest having 3 files - the main PHP handler, the template for the form and the template for the result page. The main PHP file would look something like this:

<?php

        $error_message = "";

        if ($form_submitted){

                if ($form_validated){

                        include("inc-result.txt");
                        exit;

                }else{

                        $error_message = "something went wrong!";
                }
        }

        include("inc-form.txt");
?>

if validation fails, the logic drops you back to the form, where you can display the previously entered values, along with the relevant error message.

Cal
A late entry! I hadn't considered increasing the number of files to **3** but given that my users *will* make errors the logic of your response is hard to argue with. Let me think about it.
pavium
A: 

It seems like you should do 2 things:

1) create controller that steps in to see if you are doing an edit action or a display action you already have the start of one at the top of your file there, just make it include "form.php" (your form) after it does it's business. So yes, make 2 files.

2) pull all that crappy formatting code up into the controller. Calculate all your values before the form is ever loaded. This includes running htmlspecialchars on all your form elements that need it. You can even loop through them to save lines of code:

i.e.

$cleanTheseVars = array ($a, $b, $c $error, $result);

array_walk($cleanTheseVars, 'htmlspecialchars' );

Zak
A: 

it does depend but in the long-term I would suggest separation of forms and business logic. For quick projects I do understand the short-term gain of keeping it in the same page but you never know when the form you did needs to be added with features or needs to be turned to an ajax form. If you keep your logic separate from the form you would be ready for these changes quicker.

L Digital Dash