That way, the fields automatically persist when the user’s input has an error and the form must be corrected and resubmitted. This works fine when adding records.
However, when updating an existing record, there is no $_POST array yet when the form is first displayed. So you do something like this:
$query = ‘SELECT * FROM mytable WHERE id LIKE "’ . $_GET[‘id’] . ‘’';
$result = mysql_query($query);
$fields = mysql_fetch_assoc($result);
and you change your form fields to look like this:
But now you have to move array contents between $_POST and $fields because when the user edits and submits the form, the updated info is going to $_POST, not $fields. The only way to update the display is to copy the values from $_POST to $fields.
What if instead we fetched the record directly into the $_POST array, like this?
$query = ‘SELECT * FROM mytable WHERE id LIKE "’ . $_GET[‘id’] . ‘’';
$result = mysql_query($query); $_POST = mysql_fetch_assoc($result);
That way, there’s no need to use a separate array with whatever complexity it adds. But I’ve looked all over google, and I’ve only found a couple of examples using $_POST that way, so I figure there must be something wrong with it. Is creating the $_POST array like this bad practice? Does it confuse the PHP internals somehow? It seems to work, though.
Instead of using the POST array directly use an array of the field values. That way you can swap the values in and out based on an edit or create using the same interface.
I would advise against the method cydewaze described because it not only introduces unnecessary logic into the presentation layer but lacks flexibility for making future changes. Not to mention it introduces another layer of complexity for designers that may need to modify the template to achieve a specific design goal. Also, the relationship between the domain and database is not always the same. For maximum flexibility consider the likely possibility of supporting abstracted database values.
These two posts bring up an interesting point - when is it too early to start talking about design patterns and things like “presentation” layer?
Cyde’s solution isn’t bad I think when someone is just starting to learn PHP. But in a large scale application where a design pattern is used to help maintain the software it would be verboten.
I mean, there is a limit to how much you should spring on someone who’s starting off. Introducing MVC on day one is a bit much in my opinion.
Yeah, I was by no means trying to bring up MVC directly – just provide a quick tip for making maintenance and further development a little less painful (hopefully).