Forms best practice

Hello!

I’m doing a beginners’ course on php and we’re currently working on forms. (I feel like I should say our course is very very basic so I apologize if I don’t use the correct terms or anything). I’m wondering about best practice when coding a form that sends the data to the same page.

When I do it, I like to keep the html and the php separate because it looks neater to me. So I write something like this:

<form method="post" action="form.php">
....
<input type="submit" name="ok">
</form>

<?php
if( isset($_POST["ok"]) ){
....
}

?>

My teacher says it’s better to put everything in php but didn’t explain why. So he writes:

<?php
echo "<form method=\"post\" action=\"form.php\">\n"
.....
echo "<input type=\"submit\" name=\"ok\">\n"
echo "</form>\n"

if( isset($_POST["ok"]) ){
....
}

?>

I find this solution tedious to write and difficult to read. So I was wondering if someone could tell me why it’s better to code it that way? I did some research but didn’t find anything, or at least anything I could understand.

On a side note, my teacher also said that when we use the isset function, we should press tab before writing the parameter ortherwise it doesn’t work (and didn’t explain why). That doesn’t make any sense to me since it does work without that for me and I don’t quite see what difference pressing tab would make to my code. Is there something I missed completely?

Thank you very much for your help! And I apologize if my questions are dumb

The first example you gave (your way) is the almost the normal.
Put the PHP at the top of the file and the HTML underneath.

There are arguments for both staying in PHP or ending and using HTML.
I think ultimately this will come down to personal preference.

Regarding the isset;
[php]
// all are perfectly acceptable.
if(isset($_POST[“ok”])){

if( isset($_POST[“ok”]) ){

if( isset( $_POST[“ok”] ) ){
[/php]

Again, this will be a preference thing.

One thing i would add, this line here;
[php]
echo “<form method=“post” action=“form.php”>\n”

// using single quotes you won’t need to escape using slashes.
// the \n needs to be wrapped in double quotes though.
echo ‘’ . “\n”
[/php]

Single quotes will be printed without being checked for variables etc.
Double quotes will have variables replaced with there value. IE \n = new line.

As a sidenote, you do know \n only formats the source code don’t you? (right click > view source)
(it has no effect on the visual layout of the script in your browser.)

Hope that helps,
Red :wink:

Your teacher is wrong, echoing HTML is always considered bad practise.

A very common (more advanced) pattern is called MVC, you don’t need to learn or focus on this at the moment, but it can help explain why we separate stuff. In this pattern you have:

Model:
Where your application logic resides.

View:
“Blind” html view templates. Note that with PHP we usually write these in a php file so we can echo variables, do ifs and loops, etc. But the view should never “go out” and fetch data on its own, it should not know about the database/datastore, it should not know of any APIs, etc.

Controller:
The code where you take actions from the user (urls/params), and use the Model(s) to get data and pass along to a view.

Writing code like this might be a bit overkill for a small project. But I prefer it nevertheless as it makes the code extremely structured.

Simple example:
[php]
// .htaccess

turn on apaches rewrite engine

RewriteEngine On

will silently redirect

http://yoursite.com/blog/post/157-time-to-go-again.html

to the real (and ugly) url

http://yoursite.com/Controllers/Blog.php?post=157-time-to-go-again

the user will still see the pretty url though!

RewriteRule ^blog/post/([^/]*).html$ /Controllers/Blog.php?post=$1 [L]

// Controllers/Blog.php

<?php // include some common stuff, like config, db, session, error handling, etc require_once '../Common.php'; if (isset($_GET['post'])) { // Show the specified post // Note how the controller doesn't care about how we find a post, // we just ask the PostModel to handle it for us $post = PostModel::findOneByIdSlugAndActive($_GET['post']); if (!$post) { // We didn't get a post back from the post model, // show a beautiful error message to the user! View::render('404'); } // All ok, show the post // Note how we let the View class handle how we render our views // We just pass along the template we wish to use, and any potential // parameters we want to have available in the view. View::render('Post/Single', $post); } else if (isset($_GET['cat'])) { // Show the specified category $category = CategoryModel::findByIdAndActive($_GET['cat']); if (!$category) { View::render('404'); } $posts = PostModel::findAllByCategoryAndActive($_GET['cat']); View::render('Category/Grid', array($category, $posts)); } else { // Show everything $posts = PostModel::findAllByActive(); View::render('Post/List', array($posts)); } // Models/PostModel.php <?php Class PostModel extends BaseModel { // base model sets up our db stuff with error handling private $db; public static function findAllByActive() { return self::db::query( 'SELECT * FROM post WHERE active = 1' ); } public static function findAllByIdAndActive($id) { return self::db::query( 'SELECT * FROM post WHERE id = ? AND active = 1', $id ); } public static function findAllByCategoryAndActive($categoryId) { return self::db::query( 'SELECT * FROM post WHERE category_id = ? AND active = 1', $categoryId ); } public static function findOneByIdSlugAndActive($idAndSlug) { list($id, $slug) = explode('-', $idAndSlug, 1); return self::findAllByActive($id); } } // Views/404.php

404 - page not found

// Views/Post/Single.php

<?= $post->title ?>

<?= $post->body ?>

// Views/Category/Grid.php

<?= $Category->title ?>

<?php foreach ($posts as $post) { ?>

<?= $post->title ?>

<?php } ?>
[/php]

As you can see lots of code even for this simple example (and it’s not even complete).

But! It is structured, the controllers are very slim andPso readable you don’t even need comments. With the model separated you can change the data store without having to rewrite your entire application (controllers and views stay the same). The loose coupling between controllers, models and the db also mean that you are able to test your application. Which in a professional environment is very important.

Another positive thing with not echoing html is that your IDE/editor can actually highligh the code/autocomplete/show errors when you write proper html instead of strings in PHP

I personally have lately been trying to separate PHP code from HTML as much as possible, but there are times that it unavoidable.

I also try to avoid using static methods as much as possible. Static methods allow procedural/functional code to be shoe-horned into an Object Oriented world. Using static methods and variables breaks a lot of the power available to Object-Oriented code. Again there are times that it is unavoidable for doing it the other way would make it more cumbersome.

These are just my opinions and you know what they say about opinions. ;D

To the OP, I would have the form in HTML and trust me you don’t want that to be in PHP for I have done this (sad to say pretty recently too :() and it is a pain editing, IDE’s don’t give you hint coding and like you already stated it looks messy. I really don’t understand how an instructor can say putting everything in PHP would be easier. When in fact it is the complete opposite. sigh… :’(

[member=57087]Strider64[/member] I agree on static methods. It was just to make the example as simple as possible ^^ There are situations ypu would want to use static, but my example above isnt one of them

I was going to modify my post, but thought it would be better in a new post.

If I had to do over I would separate the following:

[php] <?php
while ($entry = $result->fetch(PDO::FETCH_OBJ)) {
$displayDateAdded = new DateTime($entry->date_added);
$displayDateUpdated = new DateTime($entry->date_updated);
$timeAgo = new TimeDifference();
$highlightCode->setString($entry->message_post);
$comment = $highlightCode->getString();
echo ‘’ . “\n”;
echo ‘

’ . htmlspecialchars($entry->title) . ‘

’ . “\n”;
echo '

Created by ’ . $entry->created_by . ’ ’ . $displayDateUpdated->format(‘M d, Y @ g:i A’) . ‘

’ . “\n”;
echo ‘
’ . “\n”;
echo nl2br($comment) . “\n”;
echo ‘
’ . “\n”;
echo ‘
’ . “\n”;
if (isset($user) && $user->getUserId() == $entry->client_id) {
echo ‘EDIT’;
echo ‘Delete’;
}
echo ’

Updated ’ . $timeAgo->ago($displayDateUpdated) . ‘

’ . “\n”;
echo ‘
’ . “\n”;
echo ‘’ . “\n”;
}
?>[/php]
By that I mean the PHP from the HTML as you can see it looks pretty sloppy and it would also give it more of the View in MVC. :wink:

You see we all are guilty of sloppy coding…LOL ;D

all them echo’s - bleugh :’(

[php]
printf(’

%s


Created by %s %s



%s
’,
htmlspecialchars($entry->title),
$entry->created_by,
$displayDateUpdated->format(‘M d, Y @ g:i A’),
nl2br($comment)
);
[/php]

Red 8) :-* :stuck_out_tongue:

Thank you all for your answers! It makes much more sense like this and I’m glad to see my gut feeling was right. Forgive me for not taking part in your debate, though, I’m a bit out of my depth ;D

[member=26967]Redscouse[/member]: I completly forgot about single quotes for some reason, thanks for reminding me. It does help not to have to use all those slashes. And I knew about the \n but thanks for checking!

[member=71845]JimL[/member]: thanks for your very comprehensive answer!

[member=57087]Strider64[/member]: thank you! Sadly I’m not overly surprised that my teacher’s wrong… sigh

[member=75787]lazy_octopus[/member] np, I quickly wrote up that code for this purpose only though, so it’s nothing worth using and is probably buggy (in addition to very incomplete). It does show the thought of it though. Through separating different parts of our code we can get a structured code base that is easy to test and maintain.

As you can see by our answers, we all have a slightly different way of writing code. I say as long as it’s
readable (by humans) and/or well commented, pick a style that suits you and stick with it.

No worries, happy to help. :slight_smile:

[member=71845]JimL[/member] has given very sound advice regarding MVC.
I take this approach 99.9% of the time, it just makes sense.

Red :wink:

Sponsor our Newsletter | Privacy Policy | Terms of Service