How to separate HTML from PHP

Asked

Viewed 1,163 times

4

I read in several places that you should not mix PHP with HTML and vice versa, How then could I separate this code for example:

<?php include 'C:\xampp\htdocs\trabweb\sessaoBD.php' ?> <!--entra na sessão e na database -->

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <title>Trabalho web</title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="http://localhost/trabweb/css/style_hashbase.css"> <!--css do site N-O-D-E, apenas algumas modificações feitas -->
  <script src="js/jquery-3.2.1.min.js"></script>
  <script src="js/bootstrap.js"></script>
</head>

<body>
<?php include 'C:\xampp\htdocs\trabweb\header.html' ?> <!--cabeçalho da pagina-->

  <div id="content">
    <div id="page">
        <div id="list">
<div id="post">

  <?php if ($login === true and $_SESSION["user_name"] === "lucas"): ?> <!--checa se é o ADMIN, caso sim ele podera fazer um novo post -->
    <a href="http://localhost/trabweb/crianewpost.php">*NEW POST*</br></br></a> <!--redirige a pagina de criar um novo post  -->
    <?php endif; ?>

<!--mostra todos posts na tela -->
          <?php
          $sql =  "select titulo,id from POSTS";
          //$sql = "DELETE FROM POSTS" ;
          $result = $conn->query($sql);
          if ($conn->query($sql) === false) {
              echo "Error: " . $sql . "<br>" . $conn->error;
          }
          if ($result->num_rows > 0) {
              // output data of each row
              while ($row = $result->fetch_assoc()) {
                  echo  '<a method="get" href= "http://localhost/trabweb/db/seleposts.php?posts_id='.$row['id'].'">'.$row["titulo"].'</a> <br>'; //cada post é um link para o seu conteudo
              }
          } else {
              echo "0 results";
          }
          ?>

</div>
        </div>
      </div>
    </div>

  </body>
  </html>
  • 2

    If you want to build HTML with PHP, you essentially have to mingle the two. What you can do there is to separate things: PHP that defines PHP layout that defines logic, such as SQL execution.

  • Lucas the best way to separate php from html is by using some template framework. Currently Twig (template engine) or Blade meets this need a lot. If you are using php without framework Twig may fall very well...

  • 1

    studies about MVC a good would be using a framework called Phalcon the structure of it already allows creating layouts and its performance is the best

  • 3

    I would recommend staying well away from frameworks per hour. If you don’t master the basics, it makes no sense to want to master the advanced. As I always say, frameworks are solutions to specific problems. Using them for a different purpose is a mistake that brings more harm than good.

3 answers

8


First, using fixed paths will complicate for you to publish. On the server will not be that way.

Second, almost everything you see out there about programming is written by people who don’t understand what you’re talking about, are people who also read somewhere and keep repeating without understanding the motivator and context. It becomes a "wireless phone". Just believe in things that explain why.

It is not possible to separate completely into pages that need to be built dynamically (and it is a mistake for people to try to make everything dynamic). You can minimize the use and separate the most complex logic into another file. But it only makes sense as a way to organize everything coherently, just make a simple separation doesn’t help much, it’s just to "stick to the table".

If you need comments it is because the code is too confusing. I will not fix several problems in it, just show what was asked.

To do it right would be tricky to show here, but roughly speaking it’s abstraction of what you need to separate.

<?php include 'sessaoBD.php' ?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <title>Trabalho web</title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="css/style_hashbase.css">
  <script src="js/jquery-3.2.1.min.js"></script>
  <script src="js/bootstrap.js"></script>
</head>
<body>
<?php include 'header.html' ?>
  <div id="content">
    <div id="page">
      <div id="list">
         <div id="post">
         <?php if ($login and $_SESSION["user_name"] === "lucas"): ?>
             <a href="crianewpost.php">*NEW POST*</br></br></a>
         <?php endif;
         getPosts();
         ?>
         </div>
       </div>
     </div>
   </div>
</body>
</html>

Posts.php

<?php
function getPosts() {
    $sql =  "select titulo, id from POSTS";
    $result = $conn->query($sql);
    if ($conn->query($sql) === false) echo "Error: " . $sql . "<br>" . $conn->error;
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            echo  '<a method="get" href= "db/seleposts.php?posts_id='.$row['id'].'">'.$row["titulo"].'</a> <br>';
        }
    } else echo "0 results";
}
?>

I put in the Github for future reference.

Contrary to what is being said by others, I do not recommend studying MVC. First because it is more complicated for a beginner who is having very basic difficulty yet. Second because there is a chain that has already realized that MVC is cannon to kill bird in most web scenarios. It serves large projects with a lot of logic, where you really need to manage complexity, but for small projects, which is the overwhelming majority of cases it just adds complexity without bringing advantages, so frameworks more recent has preferred a simpler approach (and I am not recommending the use of them, old or modern).

  • It’s just a college paper, so I won’t have to publish it. "Almost everything you see out there about programming is written by people who don’t understand what you’re talking about," noted : ). the comments are because the teacher really asked. I would appreciate if you could tell me any of those mistakes. "And I’m not recommending using them, old or modern" noted. I’ll leave it at that, thanks.

  • The list is too long to list :) The basic model you are following works, the error is how to organize it the way it is done in real market situations.

  • (T_T) , : D, I’ll ask the teacher when I have the opportunity.

2

Dude, a little PHP and HTML always end up mixing, for example includes and IF can stay there quietly, what you could separate is this part:

<?php
   $sql =  "select titulo,id from POSTS";
   //$sql = "DELETE FROM POSTS" ;
   $result = $conn->query($sql);
   if ($conn->query($sql) === false) {
       echo "Error: " . $sql . "<br>" . $conn->error;
   }
   if ($result->num_rows > 0) {
       // output data of each row
       while ($row = $result->fetch_assoc()) {
           echo  '<a method="get" href= "http://localhost/trabweb/db/seleposts.php?posts_id='.$row['id'].'">'.$row["titulo"].'</a> <br>'; //cada post é um link para o seu conteudo
       }
   } else {
       echo "0 results";
   }
?>

There you have two options, either put this code in a separate file and simply include it there, or create a file and turn this code into a function, then in HTML code you just call this function.

0

I believe that a first step for you to understand this better would be to study architecture MVC, which is one of the most common software architectures. It will already open up several horizons for how your project can be well divided and organized.

In your case, as you are working with PHP, I would also recommend that you take a look at the framework Codeigniter, as well as several other frameworks, Codeigniter works with the MVC architecture, "forcing" the developer to work on it.

There are several other framework options in PHP, such as Zend, Laravel, etc. But I believe that among the majority Codeigniter is one of the ones that has the smallest learning curve, best for beginners.

  • And it’s never really going to be a rule, each case is a case, so you might have to mix PHP with HTML, don’t feel guilty about it.

  • My teacher said that these frameworks should not be used (I forgot to comment) but it does not cost to study them.

  • @lucaspelepek I understand, I believe Maniero’s response is well in fact, I hope.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.