How to echo the value of a variable from the query result

0

To automate my process of generating a JSON , I save the name of the variable in the database (Ex: $teste_value_1 ).

In my file.php I have the value of this variable, for example $teste_value_1 = "Isso é um teste"; .

Then I make a query to echo this variable, however, instead of returning the value of the variable previously provided in PHP ("This is a test"), it always returns without interpreting variable, just as text ("$ test_value_1").

Below my data structure to better understand the process:

Table: attributes

id_attribute |  attribue_string | attribute_value
1            |  teste_string_1  | $teste_value_1
2            | teste_string_2   | $teste_value_2

Variables:

$teste_value_1 = "Isso é um teste";
$teste_value_2 = "Esse é outro teste";

Query:

    $query_array = mysqli_query($connect,"
                    SELECT GROUP_CONCAT(CONCAT('{id:', a.attribute_string, ',value_name:', a.attribute_value, '}') SEPARATOR ', ') AS concat
                    FROM rel_categories_attributes AS rca
                    INNER JOIN categories AS c ON c.id_category = rca.categories_id_category
                    INNER JOIN attributes AS a ON a.id_attribute = rca.attributes_id_attribute
                    WHERE id_category = '{$id_category}'
                    ");
WHILE ($reg_cat = mysqli_fetch_array($query_array)){

echo $teste_query = $reg_cat["concat"] . ",";

Result:

{id:teste_string_1,value_name:$teste_value_1},
{id:teste_string_2,value_name:$teste_value_2},

Expected result:

{id:teste_string_1,value_name:Isso é um teste},
{id:teste_string_2,value_name:Isso é outro teste},
    
asked by anonymous 08.03.2018 / 19:56

1 answer

0

You can do this through a method called gambiarra . With this method you can call the get_defined_vars() function and it will return all declared variables. So you can fetch and replace the $nome_da_variavel value with the value returned by the database.

Commented example:

<?php

$teste_value_1 = "###########";
$teste_value_2 = "***********";

$text = '{id:"teste_string_1",value_name:"$teste_value_1"}, {id:"teste_string_2",value_name:"$teste_value_2"}';

/* Percorre todas as variáveis declaradas. */
foreach(get_defined_vars() as $variable => $value) {

    /* Verifica se o valor da variável é do tipo String */
    if (is_string($value)) {

        /* Realiza a busca e substituição */
        $text = str_replace(
                "\${$variable}",
                $value,
                $text
            );
    }
}

echo $text;
  

Obs. : This is not recommended, but in your case it will work. Ideally you could save the content in the DB.

If you know the name of the variables and if they do not change the name, just use str_replace , for example:

$text = str_replace('$teste_value_1', $teste_value_1, $text);
$text = str_replace('$teste_value_2', $teste_value_2, $text);

echo $text;
    
09.03.2018 / 09:55