How to combine PHP and HTML

For those who are not clear about it, or who want to see the different ways that exist, we are going to see with this tutorial how to combine php and html to create dynamic pages.

to understand how html and php work together It is recommended that you know or are familiar with the following web programming concepts:

  • Using variables in PHP
  • PHP control structures
  • IF and Else Conditionals
  • FOR PHP loop
  • PHP functions
  • Database connection and database reading

Content

  • Why are php and html used together
  • How can PHP use HTML?
    • Explanation with example of php combined with html
  • Example 2 Combine php with html
  • Extra: Advanced example php and html combined

Why are php and html used together

Combining php and html is a common task when developing web applications with dynamic pages. Using both languages ​​together can confuse more than one, and I often find programmers coming from other languages, and programming beginners quite confused by this issue.

PHP is a language that runs on the server, and among the many utilities it has, building pages dynamically is among the most common. Thanks to PHP we can assemble in HTML the latest blog postthe form results search or build the products html from an online store.

How can PHP use HTML?

For PHP, the HTML language is nothing more than a mere plain text, as a text could be. “Hello World”. the same thing happens with print css or other language interpreted on the client (the web visitor’s browser) such as javascript. Because? Well, because PHP is a language that runs on the server, that is, it runs long before the visitor sees the web, so when a visitor visits the page index.php of our website, the PHP programmed in this page would be executed first, then the server would send the final html page to the client, and finally the browser (the client) interprets all the content of the page (except the php that does not receive it). .

Explanation with example of php combined with html

Let’s see an example. We have a main page on our website index.phpand in this page I program in PHP the following:

<html>
<head>
     <title>Ejemplo combinar php y html</title>
</head>
<body>
<?php
for($i=0;$i<10;$i++){
    echo 'Hola ' . $i;
}
?>
</body>
</html>

Well, in this example we have a small portion of PHP in a file with HTML content. Let’s see the order of execution:

  1. The web user visits the link www.srcodigofuente.com.
  2. The server looks for the file index.php in my root directory.
  3. Apache opens the file and since it has a .php extension it scans it in case it has to execute php code.
  4. When exploring the file, it finds HTML, a language that it will ignore since it cannot be executed, and it will leave it as it is.
  5. It comes across #php and starts parsing the code it finds inside.
  6. run the for-loop which has ten iterations marked by counter $i.
  7. As in each iteration it performs a text print (threw out $i), to the content of the file, that is, what is plain text for Apache, adds the result of the ten threw out (Hello 1, Hello 2,…).
  8. Apache finishes parsing PHP when #/php is encountered and continues scanning the file which is now back to plain text (HTML).
  9. When Apache reaches the end of the file it sends it to the client. Thus, the user’s browser that visited the link on my website will now see an HTML page with a language to interpret and that it will convert into the corresponding design.

The file that the web browser has received and read will be:

<html>
<head>
     <title>Ejemplo combinar php y html</title>
</head>
<body>
Hola 1Hola 2Hola 3Hola 4Hola 5Hola 6Hola 7Hola 8Hola9
</body>
</html>

As you can see there is no trace of PHP, that portion of the file has been interpreted at the time on the server (Apache) and once the code is executed, only what has been printed in the file remains (with threw out For example).

Example 2 Combine php with html

Seeing the previous example of html and php together Now let’s see a more complex example, which reads from the database and builds, for example, the latest news from my website.

First the connection and the query of the data from the database with the class mysqli:

<?php
$objMysql = mysqli('localhost','root','root','database_blog');
$query = 'SELECT titulo, texto
               FROM noticia
               ORDER BY fecha DESC
               LIMIT 2;';
$result = $objtMysql->query($query);
$objtMysql->close();

Now, if the query went well and $result is different from false, I am going to show with HTML and PHP a #lt;article#gt; For each news:

if($result != false){
     for($i=0;$i<$result->num_rows;$i++){
           $row = $result->fetch_assoc();
          ?>
           <article>
                   <h2> <?php echo $row['titulo']; ?> </h2>
                   <p> <?php echo $row['texto']; </p>
           </article>
           <?php
     }
}
?>

Discord code appears contained in loop for. I have done a normal programming of the loop except that within it I have closed PHP, I have written HTML in the normal way (if you copy it in your IDE it will color it as html), and where I want dynamic values ​​to appear, that is, values ​​that come from of the query rows and are stored in PHP, I open PHP #php and print the value of the desired variable just before closing PHP #/php and continue writing HTML as normal. Finally I reopen PHP and respectively close the loop for, and the if.

With this code I have managed to write a piece of HTML code only once, and in the end the file that is sent to the user will have two #lt;article#gt; each one with the information of a news item. This script will adapt to the information in the database at all times, and will therefore be a dynamic page.

What a priori can be a bit confusing to see (open and close php), but it is the best way to work with html and php togetherAlso, once understood and tried, it is a true marvel. The same thing that I have done is applicable to code javascript either CSS. To understand the concept you have to practice it several times.

Extra: Advanced example php and html combined

I would like to leave an example of more advanced use (not really the truth either), of the use of html within a php function, something very useful and that you may not know if you are reading these lines:

<?php
function imprimeArticle($arrayInfo){
?>
      <article>
             <h2><?php echo $arrayInfo['titulo'] ?> </h2>
             <p> <?php echo $arrayInfo['texto'] ?> </p>
      </article>
<?php
}
?>

In this example you can see a normal PHP function, with an input parameter with the news information and, as in the previous example, an HTML printout with PHP embedded variables completely dependent on the function (it is only written if called to the function). Like if I had done a threw out of all the HTML, the final output of the function would be dynamically composed with each call and its data array input.

The function call could feed it into a database scan and you would have a cleaner version of what was programmed before:

<?php
$objMysql = mysqli('localhost','root','root','database_blog');
$query = 'SELECT titulo, texto
               FROM noticia
               ORDER BY fecha DESC
               LIMIT 2;';
$result = $objtMysql->query($query);
$objtMysql->close();
 
if($result != false){ //ha ido bien la consulta en la base de datos
     for($i=0;$i<$result->num_rows;$i++){
           $row = $result->fetch_assoc();
           imprimeArticle($row);
     }
}
?>

If it has not been clear to you, I recommend you copy all the code (the one from the last two examples) and test it with a table from your local database.

Leave a Reply