How to put a PHP code inside an HTML that is stored in a PHP variable?

Asked

Viewed 630 times

-2

I am a beginner in PHP. My intention is to create a variable that will store snippets of a DIV in HTML. However, some excerpts of this HTML contain PHP instructions, and I don’t know how to make these instructions "readable", so to speak.

My code is just below. Note that I have the variable $variavel. My problem is inside the paragraph teacher.

Grateful!

<?php

  $variavel .= ' 
                    <a href="meusite.php?id='.$row["id"].'" target="_blank">
                        <div class="grid__item large--three-tenths medium--five-tenths">
                        <img src="imagens/imagem.jpg" alt="'.utf8_encode($row["fullname"]).'" title="'.utf8_encode($row["fullname"]).'">
                        <p class="h6">'.utf8_encode($row["fullname"]).'</p>
                        <p class="professor">

/* COMO COLOCAR ESTE TRECHO? */

                        $iddocurso = $row["id"];
                        $professor = "SELECT firstname, lastname FROM mdl_course";
                        $resultProf = $conn->query($professor);
                        
                        if ($resultProf->num_rows == 1) {
                            while($row2 = $resultProf->fetch_assoc()) {
                                echo 'Professor: '.utf8_encode($row2["firstname"]).' '.utf8_encode($row2["lastname"]);
                            } 
                        } else if ($resultProf->num_rows > 1) {
                            $array_professores = array();
                            while ($row2 = $resultProf->fetch_array()){
                                $array_professores[] = utf8_encode($row2['firstname']).' '.utf8_encode($row2['lastname']);
                            }
                            $professores = implode('; ', $array_professores);
                            echo 'Professores: '.$professores;
                        } else {
                            echo "Sem professor cadastrado";
                        }
/* ATÉ AQUI */
                        
                        </p>
                        <span>Acessar</span>
                        </div>
                        </a>
  ';
  ?>

  • Important you [Dit] your question and explain objectively and punctually the difficulty found, accompanied by a [mcve] of the problem and attempt to solve. To better enjoy the site, understand and avoid closures and negativities worth reading the Stack Overflow Survival Guide in English.

2 answers

1


In php and html you should always remember that php runs before html is displayed.

Php runs on the server-side (hosting) and html run on the client-side (browser).

Then separate your code to run first in php and then put in the variable what you want to display in html.

Sort of like this:

<?php

// Primeiro execute seu php e em vez de usar "echo" para exibir durante a execução,
// coloque as variaveis para exibir depois no local que você quer q o resultado apareça:
// veja que troquei o "echo" por "$variavelderesultado" no seu código abaixo e mudei ele de posição.

    $iddocurso = $row["id"];
    $professor = "SELECT firstname, lastname FROM mdl_course";
    $resultProf = $conn->query($professor);
    
    if ($resultProf->num_rows == 1) {
        while($row2 = $resultProf->fetch_assoc()) {
            $variavelderesultado =  'Professor: '.utf8_encode($row2["firstname"]).' '.utf8_encode($row2["lastname"]);
        } 
    } else if ($resultProf->num_rows > 1) {
        $array_professores = array();
        while ($row2 = $resultProf->fetch_array()){
            $array_professores[] = utf8_encode($row2['firstname']).' '.utf8_encode($row2['lastname']);
        }
        $professores = implode('; ', $array_professores);
        $variavelderesultado = 'Professores: '.$professores;
    } else {
        $variavelderesultado = "Sem professor cadastrado";
    }

// depois que você ja executou o que queria ai sim você coloca a variavel armazenada onde deseja que apareça:

$variavel .= ' 
<a href="meusite.php?id='.$row["id"].'" target="_blank">
    <div class="grid__item large--three-tenths medium--five-tenths">
    <img src="imagens/imagem.jpg" alt="'.utf8_encode($row["fullname"]).'" title="'.utf8_encode($row["fullname"]).'">
    <p class="h6">'.utf8_encode($row["fullname"]).'</p>
    <p class="professor">

    '.$variavelderesultado.'
    
    </p>
    <span>Acessar</span>
    </div>
    </a>
  ';
  
  // E depois de tudo finalizado que você utiliza o "echo" para exibir o resultado.
  
  echo $variavel;
  
  ?>
  • 1

    Excellent explanation, Bruno!! Besides having worked perfectly, managed to understand the logic and principles you used! Thanks a lot, man!

  • @winiercape glad to have helped ^^

1

Whenever you mix html with php, follow this basic rule:

Next: If php variable is closed with double quotes "", then all html inside will have to be contained by simple quotes '', or vice versa. In addition, where a code is to be included php between the code html, you must close the quotes of the variable (double, in the case of the example below) followed by . $code . and restart the quotes of html " as in the example below.

php from within follows the same line of reasoning.

Example: My code with html and php inside a php variable:

<?php 
$variavelx = "<div class='nomedaclasse'>" . $codigophp . "</div>" . $codigophp2 . "<br>"; 
?>
  • Thanks for the answer, Amanda! I was able to understand this principle, and I even thought about it, but since it involved other code within HTML, it didn’t work. But thanks for the return!

Browser other questions tagged

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