Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice: where to put the PHP code?

Tags:

html

php

position

I do admit this question is going to be a bit vague, but I will try to explain what I'm trying to accomplish by a few examples. I have some PHP code that loads a bunch of variables from the MySQL database, contains some declarations, some functions to quickly output HTML code etc. However I would love to do all that stuff before anything is sent to the client.

So I do:

<?php
include("somefile.inc");
function bla()
{
    ...
}

if (fails)
    echo "Error: ...<br />";

?>
<!DOCTYPE>
<html>
    <head>
        <script>
            ...
            <?php echo $someString; ?>
            ...
        </script>
    </head>
    <body>
        ...
    </body>
</html>

This is all fine and ok, until I get an error. The echo will not show in the browser because it's before all HTML... So I modified:

<!DOCTYPE>
<html>
    <head>
        <script>
            ...
            <?php echo $someString; ?>
            ...
        </script>
    </head>
    <body>
        <div class="error_block">
            <?php
            include("somefile.inc");
            function bla()
            {
                ...
            }

            if (fails)
                echo "Error: ...<br />";

            ?>
        </div>

        ...

    </body>
</html>

Now I can actually see errors, which is good. But now the problem arises that in the header, or scrips, I cannot access variables that will be loaded later on in the newly created error_block.

I really don't like splitting the code in the error_clock to some above the HTML document and some in the error_block. And I also don't want to use PHP's die() function which abrubtly ends the execution.

Anyone can give their 2 cents on this issue? Thanks.

like image 309
the_source Avatar asked Jul 29 '11 13:07

the_source


1 Answers

If you're looking for an alternate solution, I have one for you. What I like doing is having the logic in before the DOCTYPE

if(error) { $error = "Please do something" }

Than, down in the document I have a div just for the error (Thanks @Dave for the input)

<?php echo $error != '' ? '<div id="error">' . $error . '</div>' : ''; ?>

This div will not appear if there isn't an error (meaning $error is empty) and it makes it easier for you to style the error message the way you would like

#error { color:red; }

If you want to get fancy, you can use some jQuery to hide/show the div so that the error doesn't have to persist.

$('#error').show().delay(7000).fadeOut();
like image 158
Phil Avatar answered Oct 08 '22 17:10

Phil