How to include a PHP variable inside a saved text in Mysql

Asked

Viewed 438 times

0

I am trying to insert PHP variables inside a text that is saved in my Mysql, so that they are automatically read in my application. First, I will explain my reality:

Printing page:

<?php
//PRIMEIRO, FAÇA A BUSCA POR ALGUNS VALORES DO BD.
//EXEMPLO: $variavel1, $variavel2, etc...
?>

//TEXTO PADRÃO EM HTML (para impressão):
// PERCEBAM QUE INCLUO AS VARIAVEIS PHP DENTRO DO TEXTO
Número do contrato: <?php echo $variavel1;?><br>
Nome: <?php echo $variavel2;?><br>
Endereço: <?php echo $variavel3;?>
//AQUI VAI O RESTANTE DO TEXTO DO CONTRATO ....

Instead of keeping this text static, so that I only change the value of the variables, I would like to register it in the comic, so that it is easier for me to change it. Being as follows:

//TEXTO SALVO NO BD:
Número do contrato: {contrato}
Nome: {nome}
etc...

DAI, when I run the application, it already automatically loads the data.

In this way, I could change both the text and the place variables. It is possible?

1 answer

1

This is a template.

Just replace "tags" with variables.

Example:

$texto_db = 'Número do contrato: {contrato}
Nome: {nome}
etc...';

echo str_replace(
    array(
        '{contrato}',
        '{nome}'),
    array(
        $variavel1,
        $variavel2),
    $texto_db
);
  • Hi Daniel, I get it! In this case, is this the way to go? There is no other way to automatically interpret variables without having to replace them?

  • And if I don’t have the exact number of variables, how can I do it that way?

  • Automation is the work of the programmer. rsrs This substitution of the above example is an "automatic" form. As for the number of variables, it is not described in the question. But there is no magic. You should create a pre-automation, assemble some standard that facilitates the routine. The above example is purely didactic. It doesn’t mean it’s the best and it’s not the only way to solve.

Browser other questions tagged

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