How to separate HTML from PHP [closed]

4

I read in several places that one should not mix PHP with HTML and vice versa, How could I then 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>
    
asked by anonymous 26.11.2018 / 16:06

3 answers

7

First, using fixed paths will complicate for you to publish. On the server it will not be this path.

Second, almost everything you see about programming is written by people who do not understand what they are talking about, they are people who also read somewhere and keep repeating without understanding the motivator and context. He turns into a "cordless phone." Just believe in things that explain why.

You can not fully separate pages that need to be built dynamically (and it's a mistake for people to try to make everything dynamic). You can minimize the use and separate the more complex logic into another file. But it only makes sense as a way to organize everything coherently, just to make a simple separation does not help much, it's just to "comply with the table".

If you need comments, it's because the code is too confusing. I'm not going to fix a lot of problems on it, just show what was asked.

To do it right it would be tricky to show here, but roughly basically it's abstraction from 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>

Postings.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 placed 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 and who is having very basic difficulties yet. Second because there is a current that has already realized that MVC is cannon to kill bird in most web scenarios. It serves large projects with lots of logic, where you really need to manage complexity, but for small projects, which is the overwhelming majority of cases it only adds complexity without bringing advantages, so newer frameworks have preferred one simpler approach (and I'm not recommending using them, old or modern).

    
26.11.2018 / 16:21
1

Dude, a bit of PHP and HTML always ends up blending, for example the includes and the IF can stay there, what you could separate is that 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";
   }
?>

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

26.11.2018 / 16:20
0

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

In your case, since you are working with PHP, I would also recommend that you take a look at the CodeIgniter framework, 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 think most of the CodeIgniter is one of the ones that has the smallest learning curve, best for beginners.

    
26.11.2018 / 16:22